Search code examples
angulartypescriptangular-materialangular-reactive-formsform-control

How to use [formControlName] with mat-checkbox


In the Angular Material documentation, they say [formControlName] cannot be used with a mat-checkbox. How can I create checkboxes dynamically according to an array of values and get checkbox value using reactive forms? Is there an alternative way?


Solution

  • Seems you misunderstood docs. formControlName work with mat-checkbox and you can create them dynamically:

    <form [formGroup]="myForm">
     <ng-container *ngFor="let field of fields">
      <mat-checkbox
        [formControlName]="field.name"
        [labelPosition]="field.labelPosition"
        [disabled]="field.disabled"
        [checked]="field.checked"
      >
       {{field.label}}
      </mat-checkbox>
     </ng-container>
    </form>