如何将 [formControlName] 与 mat-checkbox 一起使用

vsr*_*han 2 typescript form-control angular-material angular angular-reactive-forms

在 Angular Material 文档中,他们说[formControlName]不能与mat-checkbox. 如何根据值数组动态创建复选框并使用反应式表单获取复选框值?还有其他方法吗?

V.T*_*Tur 7

看来您误解了文档。formControlName 与 mat-checkbox 一起使用,您可以动态创建它们:

<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>
Run Code Online (Sandbox Code Playgroud)

  • 你不需要使用“[checked]”(检查的值是formControl的值) (3认同)