Open datepicker on input click in Angular Material




Asked on May 15, 2024
In Angular Material Datepicker, I want to open date panel on click of input box.



Replied on May 15, 2024
You can use open() method of <mat-datepicker> that opens the calendar.
Use template variable of <mat-datepicker> to call open() method on the click event of input box.
Find a sample code.

HTML code:

<mat-form-field>
  <mat-label>Select Date</mat-label>
  <input matInput [matDatepicker]="journeyDate"
        [formControl]="dateOfJourney" (click)="journeyDate.open()">
  <mat-datepicker-toggle matSuffix [for]="journeyDate" #d></mat-datepicker-toggle>
  <mat-datepicker #journeyDate></mat-datepicker>
</mat-form-field>

TS code:

import { Component } from '@angular/core';
import { MatFormFieldModule } from '@angular/material/form-field';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatNativeDateModule } from '@angular/material/core';
import { MatInputModule } from '@angular/material/input';

@Component({
  selector: 'app-item',
  standalone: true,
  imports: [MatFormFieldModule, MatDatepickerModule, MatNativeDateModule, MatInputModule, ReactiveFormsModule],
  templateUrl: 'item.component.html'
})
export class ItemComponent {
  dateOfJourney = new FormControl();
}


https://material.angular.io/components/datepicker/api



Write Answer












©2024 concretepage.com | Privacy Policy | Contact Us