localizedDate pipe in Angular

70 Views Asked by At
<mat-form-field [ngClass]="formFieldHelpers" class="flex-auto">
    <mat-label class="font-base leading-4 font-medium">
        {{ 'HEALTHWALLET.TESTINGCARD.TestedDate' | translate}}
    </mat-label>
    <input matInput [matDatepicker]="tested" name="tested" [disabled]="!isEditable || item.testId"
          [(ngModel)]='item.tested' [max]='maxDate' required>
    <mat-datepicker-toggle matSuffix [for]="tested"></mat-datepicker-toggle>
    <mat-datepicker #tested></mat-datepicker>
</mat-form-field>

I am trying to add a date pipe (localizedDate) into the ngModel attribut of the above code.

<mat-form-field [ngClass]="formFieldHelpers" class="flex-auto">
    <mat-label class="font-base leading-4 font-medium">
        {{ 'HEALTHWALLET.TESTINGCARD.TestedDate' | translate}}
    </mat-label>
    <input matInput [matDatepicker]="tested" name="tested" [disabled]="!isEditable || item.testId"
          (ngModel)="item.tested | localizedDate:'MM/dd/YYYY'" [max]='maxDate' required>
    <mat-datepicker-toggle matSuffix [for]="tested"></mat-datepicker-toggle>
    <mat-datepicker #tested></mat-datepicker>
</mat-form-field>
1

There are 1 best solutions below

2
On

According to Using Pipes within ngModel on INPUT Elements in Angular and https://angular.io/guide/template-syntax --> you can't use Template expression operators (pipe, save navigator) within template statement.

In your case, this should work :

<input matInput [matDatepicker]="tested" name="tested" [disabled]="!isEditable || item.testId"
             [ngModel]="item.tested | localizedDate:'MM/dd/YYYY'" (ngModelChange)="item.value=$event" [max]='maxDate' required>

The solution here is to split the binding into a one-way binding and an event binding - which the syntax [(ngModel)] actually encompasses. [] is one-way binding syntax and () is event binding syntax. When used together - [()] Angular recognizes this as shorthand and wires up a two-way binding in the form of a one-way binding and an event binding to a component object value.
The reason you cannot use [()] with a pipe is that pipes work only with one-way bindings. Therefore you must split out the pipe to only operate on the one-way binding and handle the event separately.