I have 2 material datepickers in my component. Each one of them is in different mat-tab
.
The date picker of first tab should be as MM/YYYY
, the second one should a normal date DD/MM/YYYY
.
The first step of changing the value of datepicker to MM/YYYY
is as follows:
export const MY_FORMATS = {
parse: {
dateInput: 'MM/YYYY',
},
display: {
dateInput: 'MM/YYYY',
monthYearLabel: 'MMM YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MMMM YYYY',
},
};
And:
<mat-form-field>
<input matInput formControlName="invoiceDate" [matDatepicker]="picker" placeholder="Choose the Month">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker startView="year" (yearSelected)="getSelectedYear($event)"
(monthSelected)="getSelectedMonth($event, picker)">
</mat-datepicker>
</mat-form-field>
The main problem is when I added the second datepicker
in my second mat-tab
. Where the format MM/YYYY
is used for all existing datepickers.
What I treid to do is to declare an exported variable as follows:
export let tab = 1;
And did two formats:
export const MY_FORMATS = {
parse: {
dateInput: 'MM/YYYY',
},
display: {
dateInput: 'MM/YYYY',
monthYearLabel: 'MMM YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MMMM YYYY',
},
};
export const MY_FORMATS_RECEIPTS = {
parse: {
dateInput: 'DD/MM/YYYY',
},
display: {
dateInput: 'DD/MM/YYYY',
monthYearLabel: 'MMM YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MMMM YYYY',
},
};
And at the providers part:
providers: [
{
provide: DateAdapter,
useClass: MomentDateAdapter,
deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS]
},
{provide: MAT_DATE_FORMATS, useValue: tab==0?MY_FORMATS:MY_FORMATS_RECEIPTS},
],
I am updating the tab
on mat-tab
click using:
<mat-tab-group (click)="getTab($event.which)">
And:
getTab(tab){
tab = tab
}
I may be missed the concept of exported consts and variables, but this is the only solution I have and it didn't work.
If I've already declared tab as 0, it will take the first format, and when the component is loaded, and tab 1 is selected, nothing is changed.