angulartypescriptangular-reactive-formsngfor

Angular: property binding with the property name constructed inside the loop


I have multiple properties:

tier1_eligibility: FormControl<boolean>;
tier2_eligibility: FormControl<boolean>;
tier3_eligibility: FormControl<boolean>;

which I want to bind to checkboxes. How can I do this with ngFor? I tried:

<mat-checkbox *ngFor="let tier of [1,2,3]"
      [formControl]="myForm.controls.tier{{tier}}_eligibility"    <- Problem here !!
></mat-checkbox>

But it's not working - it's a problem of replacing {{tier}} with the appropriate number. What would be the appropriate syntax for this?


Solution

  • Assume that the <mat-checkbox> is wrapped in a FormGroup, you can formControlName instead of [formControl].

    <form [formGroup]="myForm">
      <mat-checkbox 
        *ngFor="let tier of [1,2,3]"
        formControlName="tier{{tier}}_eligibility">
      </mat-checkbox>
    </form>
    

    Demo @ StackBlitz