I have included my code snippet below. I am utilizing mat-datepicker and customizing it to function as a year picker. The problem arises when I add
name="control" #control="ngModel" [(ngModel)]=""
to my control, as it throws an error in the console. However, when I remove name="control" #control="ngModel" [(ngModel)]=""
the control works properly.
<input class="form-control" name="FDConversationDateYear" #FDConversationDateYear="ngModel" [(ngModel)]="objCompanyFinancialDetails.FDConversationDateYear" [matDatepicker]="dp" placeholder="Month and Year" [formControl]="date" required>
<mat-datepicker-toggle class="datepicker-toggler" matSuffix [for]="dp"></mat-datepicker-toggle>
<mat-datepicker #dp
startView="multi-year"
(yearSelected)="chosenYearHandler($event, dp)"
panelClass="example-month-picker">
</mat-datepicker>
The component.ts file is as follows:
import {Component} from '@angular/core';
import {FormControl} from '@angular/forms';
import {MomentDateAdapter} from '@angular/material-moment-adapter';
import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '@angular/material/core';
import {MatDatepicker} from '@angular/material/datepicker';
import * as _moment from 'moment';
import {default as _rollupMoment, Moment} from 'moment';
const moment = _rollupMoment || _moment;
export const MY_FORMATS = {
parse: {
dateInput: 'MM/YYYY',
},
display: {
dateInput: 'YYYY',
monthYearLabel: 'MMM YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'YYYY',
},
};
@Component({
selector: 'datepicker-views-selection-example',
templateUrl: 'datepicker-views-selection-example.html',
styleUrls: ['datepicker-views-selection-example.css'],
providers: [
{provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE]},
{provide: MAT_DATE_FORMATS, useValue: MY_FORMATS},
],
})
export class DatepickerViewsSelectionExample {
date = new FormControl(moment());
chosenYearHandler(normalizedYear: Moment, datepicker: MatDatepicker<Moment>) {
const ctrlValue = this.date.value;
ctrlValue.year(normalizedYear.year());
this.date.setValue(ctrlValue);
}
}
Here are the errors from my console: