In my Angular 5 app I use the DatePicker from the Material Design (mat-datepicker). The default behavior of the datepicker works, but I have no way to preset a date and reset it in the associated input element. Could anyone help? Thanks. The datepicker resides in another containing component (snippet 1).
Snippet 1 (containing page):
<div class="row">
<div class="col col-md-4 col-sm-4">
<matDatepicker [initDate]="newVisitDate" (newDatePickedEvent)="setNewVisitDate($event)"></matDatepicker>
</div>
<div class="col col-md-3 col-sm-3">
<input [ngModel]="newVisitDate | date:'MM/dd/yyyy'" (ngModelChange)="setNewVisitDate($event)" class="form-control" type="date" name="newVisitDate" id="newVisitDate" #newVisitDateVar="ngModel" />
</div>
</div>
Snippet 2 (mat-datepicker.html):
<div class="datepicker-container">
<mat-form-field>
<input disabled matInput [matDatepicker]="pickedDate" (dateChange)="newDatePicked($event)" placeholder="New Visit Date" id="matSelectedDate">
<mat-datepicker-toggle matSuffix [for]="pickedDate"></mat-datepicker-toggle>
<mat-datepicker disabled="false" #pickedDate [startAt]="someDate"></mat-datepicker>
</mat-form-field>
</div>
Snippet 3 (mat-datepicker.ts):
import {
Component,
Output,
EventEmitter,
Input,
OnInit
} from '@angular/core';
import {
MatDatepickerInputEvent
} from '@angular/material';
/** @title Basic datepicker */
@Component({
selector: 'matDatepicker',
templateUrl: 'mat-datepicker.html',
styleUrls: ['mat-datepicker.css']
})
export class matDatepickerComponent implements OnInit {
@Input() initDate: Date;
@Output() newDatePickedEvent: EventEmitter <Date> = new EventEmitter();
someDate: Date;
ngOnInit() {
if (this.initDate === undefined) {
this.someDate = new Date();
console.log('matDatepicker.ngOnInit.initDate(using new Date())=', this.someDate);
} else {
this.someDate = this.initDate;
console.log('matDatepicker.ngOnInit.initDate(using @input)=', this.someDate);
}
}
newDatePicked(event: MatDatepickerInputEvent <Date> ): void {
console.log('emitting matDatepickerCompont.newDatePicked()', event.value);
this.newDatePickedEvent.emit(event.value);
}
}