【问题标题】:How to generate and validate input text box dynamically when checkbox is selected选中复选框时如何动态生成和验证输入文本框
【发布时间】:2019-01-27 17:18:52
【问题描述】:

I have to handle multiple checkbox in reactive form with selection options as "W9", "F9", "other" and when "other" is selected, then a text box should get open, also required validation is needed for this .当我提交这个时,我应该得到输出为 {"Role":{W9:true, other:true,otherValue:value}}

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');
  }

HTML 文件

  <label>Role</label>

  <div  *ngFor="let control of role.controls; let i = index;">
    <input  type="checkbox"  
    [formControl] = "control">
    <label>{{roles[i]}}</label>

我只能根据复选框的选择获得真假数组,而没有其他值。

【问题讨论】:

  • 请创建一个展示此问题的 StackBlitz。

标签: angular angular-reactive-forms


【解决方案1】:

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

Roles = [
    { id: true, description: 'W9' },
    { id: true', description: 'F9' },
    { id: true, description: '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>

【讨论】:

    猜你喜欢
    • 2015-05-27
    • 2017-01-26
    • 2012-11-12
    • 1970-01-01
    • 1970-01-01
    • 2016-10-07
    • 2011-06-29
    • 1970-01-01
    • 2023-03-11
    相关资源
    最近更新 更多