选中复选框时如何动态生成和验证输入文本框

时间:2019-01-27 17:18:52

标签: angular angular-reactive-forms

我必须处理反应形式的多个复选框,选择选项为“ W9”,“ F9”,“其他”,并且当选择“其他”时,应打开一个文本框,为此还需要验证。当我提交此文件时,我应该得到的输出为{“ Role”:{W9:true,other:true,otherValue:value}}

childObject.transform.parent.gameObject

HTML文件

ngOnInit() {
    this.customerForm = this.fb.group({

      Roles: this.buildRoles()
    }) 

buildRoles() {
    const arr = this.roles.map(role => {

      return this.fb.control(false);
   });

   console.log(this.fb.array(arr));
   return this.fb.array(arr);
 }

get role() {
    return <FormArray>this.customerForm.get('roles');
  }

基于复选框的选择,我只需要获取true和false即可。

1 个答案:

答案 0 :(得分:0)

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

Roles = [
    { id: true, description: 'W9' },
    { id: true', description: 'F9' },
    { id: true, description: 'other' },
  ];

选中和取消选中的功能以及选中“ other”时显示另一个文本字段的逻辑

  updateChkbxArray(chk, isChecked): void {
    const chkArray = <FormArray>this.customerForm.get('Roles');
    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);
    }
    if (chk.description === 'other') ) {
      // show/hide another textbox
     this.otherValue = true
    }
  }

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

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