I have a component that contains many date inputs. All of them, but one, will use the standard format (MM/DD/YYYY). I read here, which helped me figure out how to get the customFormat (MM/YYYY) I wanted, but now it shows on every date input because of the provider 'useValue' on the component level. Which lead me to this question I cannot find a proper answer for. How can I have multiple formats on the same component?
On the TypeScript:
export const COMMISSION_DATE_FORMATS = {
parse: {
dateInput: 'MM/YYYY',
},
display: {
dateInput: 'MM/YYYY',
monthYearLabel: 'MMM YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MMMM YYYY',
},
};
...
providers: [
{ provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },
{ provide: MAT_DATE_FORMATS , useValue: COMMISSION_DATE_FORMATS },
]
On the UI:
One requiring custom format (displays properly)
<mat-form-field>
<input matInput [matDatepicker]="dSaleMonthPicker" placeholder="Commission Month & Year" formControlName="dSaleMonth">
<mat-datepicker-toggle matSuffix [for]="dSaleMonthPicker"></mat-datepicker-toggle>
<mat-datepicker #dSaleMonthPicker startView="multi-year" (yearSelected)="commissionDateYearHandler($event)" (monthSelected)="commissionDateMonthHandler($event, dSaleMonthPicker)">
</mat-datepicker>
</mat-form-field>
Others requiring standard format (but they are also displaying with custom format)
<mat-form-field>
<input matInput formControlName="dSold" [matDatepicker]="dSoldPicker" placeholder="Sold Date" matTooltipPosition="below">
<mat-datepicker-toggle matSuffix [for]="dSoldPicker"></mat-datepicker-toggle>
<mat-datepicker #dSoldPicker [startAt]="dSold"></mat-datepicker>
</mat-form-field>
I know with the formControlName I can't use typical "piping" from Angular, so how can I have multiple formats on the same component? Perhaps there is a way to add the custom format directly on the input? Any help is greatly appreciated.
I found the best answer here. Basically, we need to create multiple directives with different formats and attach the desired directive to the datepicker.
Working example with MomentDateAdapter can be found here (thanks to Abishek from above link).
Working example with NativeDateAdapter can be found here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With