'How to select only year on mat-datepicker
I'm developing an application with angular 8 in which I have an input that contains only year number. I have used mat-datepicker and want only to choose year.
<mat-form-field class="input-control">
<input matInput placeholder="{{'enter'|translate}}.." [formControl]="form.controls.openedAt"
[matDatepicker]="date" readonly>
<mat-datepicker-toggle matSuffix [for]="date"></mat-datepicker-toggle>
<mat-datepicker #date startView="multi-year"></mat-datepicker>
</mat-form-field>
this code shows year view first, but when I choose the year, the month view will be opened, then days view.
So how can I select only year, or show only year view on mat-datepicker?
Solution 1:[1]
This feature is not fully implemented yet. You can see that here:
https://github.com/angular/components/issues/4853
For now you can try this:
Solution 2:[2]
I did like this:
html:
<mat-form-field
appearance="outline">
<mat-label>Ano</mat-label>
<input [(ngModel)]="selectYear" [formControl]="dateForm" matInput
[matDatepicker]="picker" />
<mat-datepicker-toggle matSuffix [for]="picker" ></mat-datepicker-
toggle>
<mat-datepicker
#picker
startView="multi-year"
(yearSelected)="chosenYearHandler($event, picker)"
></mat-datepicker>
</mat-form-field>
component:
export const MY_FORMATS = {
parse: {
dateInput: 'YYYY',
},
display: {
dateInput: 'YYYY',
monthYearLabel: 'YYYY',
monthYearA11yLabel: 'YYYY',
},
};
, providers: [ { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS] },
{provide: MAT_DATE_FORMATS, useValue: MY_FORMATS},
]
chosenYearHandler(ev, input){
let { _d } = ev;
this.selectYear = _d;
input._destroyPopup()
}
Its works well and very simple!!!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Tushar |
Solution 2 |