How to integrate a toggle switch into an Angular datepicker component

Can the toggle switch be placed inside the calendar? I would like to have it positioned at the top of the open calendar so that users can choose to view date details using the toggle switch

<form #uploadForm="ngForm" (keydown.enter)="$event.preventDefault()">
  <div class="input-wrapper">
    <mat-form-field>
      <input
        id="date"
        name="date"
        [disabled]="datePickerDisabled || uploadForm.submitted"
        [matDatepicker]="datepicker"
        placeholder="Expiration date"
        autocomplete="off"
        matInput
        required />
      <mat-datepicker-toggle matSuffix [for]="datepicker"></mat-datepicker-toggle>
      <mat-datepicker touchUi #datepicker></mat-datepicker>
    </mat-form-field>
    <div class="tooltip">This field is required.</div>
    <mat-slide-toggle
      (change)="setMaxExpirationDate($event)">Show Date Details</mat-slide-toggle>  
  </div>
</form>

Answer №1

There are two approaches that you can take:

1. Customize the header by referring to the documentation: customizing header

Replicate the header from this SO answer:

/** Custom header component for datepicker. */
@Component({
  selector: 'example-header',
  template: `
<mat-slide-toggle
      (change)="setMaxExpirationDate($event)">Show Date Details</mat-slide-toggle> 
  <div class="mat-calendar-controls">
    <button mat-button type="button" class="mat-calendar-period-button"
            (click)="currentPeriodClicked()" [attr.aria-label]="periodButtonLabel"
            cdkAriaLive="polite">
      {{periodButtonText}}
      <div class="mat-calendar-arrow"
           [class.mat-calendar-invert]="calendar.currentView != 'month'"></div>
    </button>

    <div class="mat-calendar-spacer"></div>

    <ng-content></ng-content>

    <button mat-icon-button type="button" class="mat-calendar-previous-button"
            [disabled]="!previousEnabled()" (click)="previousClicked()"
            [attr.aria-label]="prevButtonLabel">
    </button>

    <button mat-icon-button type="button" class="mat-calendar-next-button"
            [disabled]="!nextEnabled()" (click)="nextClicked()"
            [attr.aria-label]="nextButtonLabel">
    </button>
  </div>
</div>  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ExampleHeader extends MatCalendarHeader<any> {

  /** Handles user clicks on the period label. */
  currentPeriodClicked(): void {
    this.calendar.currentView = this.calendar.currentView == 'month' ? 'multi-year' : 'month';
  }
}

(Make changes in the .html file to customize the controls as needed)

2. Put the mat-datepicker inside a mat-menu, as demonstrated in this another SO answer

Updated Accessing an element of the header might be challenging, but controlling the toggle is easier if you use an intermediate service. Imagine having a service like this:

@Injectable({
  providedIn: "root"
})
export class CalendarService {
  private _event = new Subject<void>();
  public onEvent = this._event as Observable<any>;
  constructor() {}

  command(value: any) {
    this._event.next(value);
  }
}

You can inject the service in the constructor of customHeader:

constructor(
    private _calendar: MatCalendar<D>,
    private _dateAdapter: DateAdapter<D>,
    @Inject(MAT_DATE_FORMATS) private _dateFormats: MatDateFormats,
    cdr: ChangeDetectorRef,
    private service: CalendarService
  )

Then, if our toggle calls a function:

<mat-slide-toggle #toggle (change)="toggleChange($event)">
    Show Date Details
</mat-slide-toggle>

The function would look like this:

  toggleChange(event: any) {
    this.service.command(event);
  }

In the ngOnInit function of the component, subscribe to the service:

ngOnInit() {
    this.service.onEvent.subscribe(res => {
      console.log(res.checked);
    });
  }

You can see an example on stackblitz

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create a right-to-left (RTL) CSS file within a create-react-app project and dynamically switch between them depending on changes

I am currently working on a multi-language project using create-react-app. My goal is to incorporate a library like "cssJanus" or "rtlcss" to transform the Sass generated CSS file into a separate file. This way, I can utilize the newly created file when sw ...

Can data be retrieved from an Excel or CSV file using only an HTML5 Local database, without relying on Mysql?

Here's a scenario: I currently have an HTML form displayed on a webpage. My goal is to gather all the information submitted by users through this form and organize it into an Excel or CSV sheet. Is this achievable using only HTML 5, or will I need a ...

Using knockoutjs to call a component on the home page

I am currently facing some challenges with knockoutjs components, as I am following the guidance provided in the official knockout component documentation. Could someone please advise me on how to correctly invoke my widget component on the main page? It ...

What is the best approach for designing a UI in Angular to showcase a matrix of m by n dimensions, and how should the JSON format

click here for a sneak peek of the image Imagine a matrix with dimensions m by n, containing names on both the left and top sides. Remember, each column and row must be labeled accordingly. ...

Tips for dividing echo output from PHP into two separate divs using jQuery AJAX

I am trying to display two different echoes from PHP in separate divs within my AJAX success function. $.ajax({ url: 'counter.php', type: 'POST', data: { some_data:some_data ...

Ionic app encountering issues with Facebook OAuth login functionality

Currently, I am implementing Facebook Auth for my Ionic app by using the Firebase module. Despite setting up the firebase module correctly initially, I keep encountering an error during the login process. It should be noted that the login function worked p ...

Apply a 2 pixel top border to an HTML table

Is there a way to add a double border at the headcell without using background images? Currently, I have a white color border top and want to add a grey color border on top of the white one. Is it possible to achieve something like #ccc and #fff for borde ...

How to perfectly align an element within a div using Bootstrap

Utilizing bootstrap here. Currently trying to center the h1 element within the div, but so far I have been unsuccessful. It consistently remains aligned to the left. Attempts have included using bootstrap's center-block helper class, as well as the fl ...

Implementing functionality: Removing a row and applying a CSS class upon button click

Check out the fiddle below: https://jsfiddle.net/shaswatatripathy/enq0kfqL/2/ I need help with creating a remove function and adding a CSS class to a clicked row. 1. When I click on "remove", the clicked row should be deleted. When I click on a row, ...

The Laravel error message "Attempting to access 'index()' on a null object"

After generating a model in Laravel, I attempted to migrate the table using 'php artisan migrate', but encountered an error message on the terminal: "Call to a member function index() on null" ...

Preventing going back to a previous step or disabling a step within the CDK Stepper functionality

In my Angular application, there is a CdkStepper with 4 steps that functions as expected. Each step must be completed in order, but users can always go back to the previous step if needed. For more information on CdkStepper: https://material.angular.io/cd ...

What is the best way to shorten string values that exceed a certain length?

Here is an array list I have: $myarray = array( array( 'name' => 'File name 1 - type.zip', 'size' => '600KB', ), array( 'name' => 'File name 2 - type.pdf&a ...

Discovering the current page using ons-navigator in Onsen UI

I am currently attempting to determine the page I am on while using the popPage() function with Onsen UI's ons-navigator. I have tried the following methods, but they always return false regardless: this.navigator.nativeElement.popPage().then((page: a ...

The website is unresponsive to the media query

Currently, I am working on a project using Windows 10, Codeigniter, jQuery, and Firefox 43.0.4. However, I am facing an issue that is quite baffling to me. My goal is to apply styles specifically for an iPad-sized window, so I have implemented the followin ...

Creating a CSS layout that eliminates the need for a vertical scroll bar

Currently, I am experimenting with creating an HTML CSS Layout using the div tag. You can view the code here Currently, the layout displays a vertical bar that I would like to eliminate. Ideally, I only want it to display if the content is lengthy. ...

What is the method for altering the text color within a disabled input field?

Currently facing difficulty in changing the color of the text within the input field when it's disabled. I'm utilizing Material UI for this purpose. import React from "react"; import { makeStyles } from "@material-ui/core/st ...

How can a method be called from a sibling component in Angular when it is bound through the <router-outlet>?

In my current project, I have implemented an application that utilizes HTTP calls to retrieve data from an API endpoint and then displays it on the screen. This app serves as a basic ToDo list where users can add items, view all items, delete items, and pe ...

The functionality is verified in Postman, however, it is not functioning properly when accessed from my client's end

I am working on a project where I have a button in my client's application that is supposed to delete a document from a MongoDB collection based on its ID. Here is the backend code for this functionality: index.js: router.post('/deletetask' ...

Issues with CSS styling are affecting the display of a form

Hey there! I was working on creating an order form for my website, and everything was going smoothly until I hit a snag while styling the webpage. The problem is that the legends of the form are extending all the way to the right side of the page, and the ...

What advantages does NgRx offer that Signal does not provide?

Signals are a recent addition to the Angular framework. In comparison to Signals, what unique benefits does the NgRx component store or other state management options provide? Are there any functionalities offered by the NgRx component store that cannot ...