Angular:有条件地改变 FormControl

Mel*_*Dsz 0 javascript typescript form-control angular angular4-forms

我正在基于切换值创建表单组验证

public toggle:boolean=false;


ngOnInit(): void {
          this.formGroup = this.formBuilder.group({
          formArray: this.formBuilder.array([
            this.formBuilder.group({
              toggleFormCtrl: [this.toggle, null],
              fnameFormCtrl: ['', this.checkInputs.bind(this)],
              lnameFormCtrl: ['', this.checkInputs.bind(this)],
              addressFormCtrl: ['', this.checkMiInput.bind(this)]
            }),
         ])
       });

  }

checkInputs(c: FormControl) {
if (this.toggle) {
  return c.value === '' ? null : {
    checkinputs: {
      valid: false
    }
  };
} else {
  return c.value ? null : {
    checkinputs: {
      valid: false
    }
  };
}

}



checkMiInput(c: FormControl) {
    if (this.toggle) {
      return c.value ? null : {
        checkMiInput: {
          valid: false
        }
      };
    } else {
      return c.value === '' ? null : {
        checkMiInput: {
          valid: false
        }
      };
    }
  }
Run Code Online (Sandbox Code Playgroud)

根据切换值,我想验证表单。当切换值为 时true,表单应该验证 formControl addressFormCtrl,当切换值为 false 时,它​​应该验证fnameFormCtrl,但lnameFormCtrl 我的代码无法正常工作。我缺少什么?

Deb*_*ahK 6

我使用如下方法打开/关闭验证:

setNotification(notifyVia: string): void {
    const phoneControl = this.customerForm.get('phone');
    if (notifyVia === 'text') {
        phoneControl.setValidators(Validators.required);
    } else {
        phoneControl.clearValidators();
    }
    phoneControl.updateValueAndValidity();
}
Run Code Online (Sandbox Code Playgroud)

此代码用于setValidators设置控件的验证器并clearValidators清除控件的验证器。

就您而言,您需要为多个控件关闭和打开它。

另请注意updateValueAndValidity. 这是确保验证器实际更改所必需的。

该代码是从ngOnInit方法中调用的,代码如下:

    this.customerForm.get('notification').valueChanges
                     .subscribe(value => this.setNotification(value));
Run Code Online (Sandbox Code Playgroud)

如果用户更改单选按钮,则执行notification该方法中的代码并调用.subscribesetNotification