Reputation: 3207
I am working to create a form which will have controls rendered provided via API. The form is rendered without any issue. However formControlName
property is missing from HTML when it is rendered. This causes issue with mat-datepicker
. Since it requires the formControlName
be associated with the control
Here is my template
<div *ngFor="let item of list; let i=index;">
<mat-form-field appearance="fill">
<mat-label>{{item.control["Caption"]}}</mat-label>
<input *ngIf="(item.control['Type'] == "Text")" matInput formControlName="{{item.key}}" >
<input *ngIf="item.control['Type'] == 'Date'" matInput [matDatepicker]="i" placeholder="DD/MM/YYYY" [formControlName]="item.key" >
<mat-datepicker-toggle *ngIf="item.control['Type'] == 'Date'" matSuffix [for]="i"></mat-datepicker-toggle>
<mat-datepicker *ngIf="item.control['Type'] == 'Date'" #i></mat-datepicker>
</mat-form-field>
</div>
</form>
Now the issue is that date control is rendered but calendar pop up does not appear on clicking calendar icon on control. However, if I input date manually in the control then it gets submitted correctly.
What am I missing here. I need to be able to bind mat-datepicker
with any and all date controls that are rendered.
Upvotes: 0
Views: 556
Reputation: 2396
Update your template like this:
<div *ngFor="let item of list; let i=index">
<mat-form-field appearance="fill">
<mat-label>{{item.control["Caption"]}}</mat-label>
<input *ngIf="item.control['Type'] == 'Text'" matInput [formControlName]="item.key" >
<ng-container *ngIf="item.control['Type'] == 'Date'">
<input matInput [matDatepicker]="i" placeholder="DD/MM/YYYY" [formControlName]="item.key" >
<mat-datepicker-toggle matSuffix [for]="i"></mat-datepicker-toggle>
<mat-datepicker #i></mat-datepicker>
</ng-container>
</mat-form-field>
</div>
Here I used ng-container
because it doesn't add additional tag in the DOM, you can also use div
here but that would have added new tag in the DOM. You can inspect elements and see the difference.
Your can read more about ng-container
here
Upvotes: 2