使用“新FormControl”处理复选框

时间:2019-01-27 05:43:04

标签: angular checkbox

基本上,我不知道如何从具有复选框的*ngFor处理该主题。我通常会知道如何使用[(ngModel)],但我不知道如何使用反应形式。 我想根据变量“ aUsers”中的内容关联我的复选框,并标记“ check”属性中的元素。 我该怎么办?

this.ValidacionReunion = new FormGroup({
  observaciones:new FormControl(null, []),
  arrayElements: new FormControl.array([])  //this is the name of my checkboxlist
});

aUsers:any=
[
  {
    "name":"xds",
    "userusuario":2,
    "check":true
  },
  {
    "name":"xdsx",
    "iduser":2,
    "check":false
  }      
]

。 。 。

<!-- obviously this is inside:<form [formGroup] = "ValidationReunion"> -->
<li  class="list-group-item waves-light"  *ngFor="let user of aUsers" >
 <input type="checkbox" formControlName="user.check">{{user.name}} {{user.iduser}}      
</li>

3 个答案:

答案 0 :(得分:0)

您应该像这样创建FormControl数组

component.ts

const control = this.aUsers.map(c=> new FormControl(c.check));

this.ValidacionReunion = this.fb.group({
  observaciones:'',
  arrayElements: this.fb.array(control)

});

component.html

<form [formGroup]="ValidacionReunion">
    <li formArrayName="arrayElements" class="list-group-item waves-light" *ngFor="let control of ValidacionReunion.get('arrayElements').controls; let i = index">
        <input type="checkbox" [formControlName]="i">{{aUsers[i].name}}      
</li>
</form>

示例:https://stackblitz.com/edit/angular-7gjkgr

答案 1 :(得分:0)

在子控件中,将表单控件名称的值设置为user.check

如果您的formControlName为'userCheck',则从formGroup内的组件类中,设置userCheck:user.check。如果是这样,则将复选框的值设置为true。

答案 2 :(得分:0)

在.ts文件中,为角色创建一个数组

Roles = [
    { id: true, description: 'W9' },
    { id: true', description: 'F9' },
    { id: true, description: 'other' },
  ];
this.customerForm = this.fb.group({
      roles: this.fb.array([]),
    });

检查和取消检查功能

  updateChkbxArray(chk, isChecked, key): void {
    const chkArray = <FormArray>this.customerForm.get(key);
    if (isChecked) {
      // sometimes inserts values already included creating double records for the same values -hence the defence
      if (chkArray.controls.findIndex(x => x.value === chk.id) === -1)
        chkArray.push(new FormControl(chk.id));
    } else {
      const idx = chkArray.controls.findIndex(x => x.value === chk.id);
      chkArray.removeAt(idx);
    }
  }

当前,我在“角形材质”复选框中显示该复选框。您可以拥有自己的复选框。

 <mat-checkbox *ngFor="let role of Roles" formArrayName="roles"
                               (change)="updateChkbxArray(role, $event.checked, 'roles')"
                                [value]="role.id">{{role.description}}
                  </mat-checkbox>