Since my text and date inputs on an Angular form (built with *ngFor
) have all the same styling (except for the type of input, of course), I want to combine them to make them easier to maintain. So I have done the following:
<div *ngFor="let form of source">
<div [ngSwitch]="form.type">
<mat-form-field *ngSwitchDefault>
<mat-label>{{form.displayName}}</mat-label>
<ng-container [ngSwitch]="form.format">
<input *ngSwitchDefault matInput formControlName="{{form.displayName}}" otherAttributes
[attr.matDatepicker]="form.type === 'date' ? 'picker' : null">
</ng-container>
<mat-datepicker-toggle *ngIf="form.type === 'date'" matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
</div>
</div>
I originally tried this without the attr.
on the matDatepicker
in the input
, but then the compiler complains that Type 'string | null' is not assignable to type 'MatDatepickerPanel<MatDatepickerControl<any>, any, any>'.
Using attribute binding is supposed to drop the attribute altogether when it evaluates to null
or undefined
, but when I do it this way, it compiles fine but the browser fails with Attempted to open an [sic] MatDatepicker with no associated input
when I click the datepicker toggle, so it would seem it fails to set the attribute in either case. I get this result whether I have quotes around picker
in the expression or not, since the rules for attribute binding specify that it should evaluate to a string.
Does this mean that attribute binding won't work for this situation? What else might I be doing wrong here? Is there some other trick I can use to base the text and date inputs on the same definition, or am I going to have to write and maintain almost identical definitions for these two controls?
Edit: Oh, and if I don't make it optional, then it forces all my non-date inputs to only take date inputs.