Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Apply Multiple MAT_DATE_FORMATS On Same Component

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>

enter image description here

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>

enter image description here

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.

like image 965
Briana Finney Avatar asked Dec 05 '18 01:12

Briana Finney


1 Answers

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

like image 162
Learning Avatar answered Oct 04 '22 05:10

Learning