Reputation: 117
I have a form which contain a list of checkboxes.
I want to display a form input in front of each checkbox when this checkbox is checked
This is my html :
<div class = "checkbox">
<label formArrayName="coverages" *ngFor="let coverage of coverageFormArray.controls;let i = index; let val of coverageFormArray.value;">
<input type="checkbox" kendoCheckBox [formControlName]="i"/>
{{coveragestypes[i]}}
<div *ngIf="val">
<input type = "text">
</div>
</label>
</div>
But here the form input is always displayed even the checkbox is checked or not! I think the problem is related to the directive ngFor where I put two loops let coverage of coverageFormArray.controls
and let val of coverageFormArray.value
? Can anyone help me please ?
Upvotes: 1
Views: 9977
Reputation: 1093
You can't use multiple *ngFor
s in the same element as those are structural directives and angular handles them in a specific way (basically for each structural directive it creates an ng-template
element which then holds the directive itself, you can read more about it here:
https://angular.io/guide/structural-directives, understanding that really makes it very clear why we can't have multiple structutral directives on the same element).
So you cannot use two ngFor
s on the same element, but you can use the index, if both arrays are of the same size, to check whether or not there is a value.
You did not give an example of the data format, so I'm probably going to give an example that will have to be adapted.
<div class = "checkbox">
<label formArrayName="coverages" *ngFor="let coverage of coverageFormArray.controls;let i = index;">
<input type="checkbox" kendoCheckBox [formControlName]="i"/>
{{ coveragestypes[i] }}
<div *ngIf="coverage.value">
<input type = "text">
</div>
</label>
</div>
In addition, I recommend using ng-container
instead of html tag that are only use to apply an Angular directive.
So my final solution would be.
<div class = "checkbox">
<label formArrayName="coverages" *ngFor="let coverage of coverageFormArray.controls;let i = index;">
<input type="checkbox" kendoCheckBox [formControlName]="i"/>
{{ coveragestypes[i] }}
<ng-container *ngIf="coverage.value">
<input type = "text">
</ng-container>
</label>
</div>
Upvotes: 2