删除反应式形式的验证器 Angular

问题描述 投票:0回答:1

我有一个条件,如果为真,我想为某些表单添加一系列验证,当条件不为真时,它将删除验证器。

现在,当我添加验证器时,它可以正常工作,但是当我尝试删除它时,它没有正确删除!!!

//html

<div [formGroup]="form">
    <p-checkbox (onChange)="changeShouldEnter()" name="shouldEnter" [value]="true"
          formControlName="shouldEnter"></p-checkbox>
    <label class="radio-lable mx-2">text</label>
</div>

//打字稿

  ngOnInit(): void {    
    this.form = new FormGroup({
      shouldEnter: new FormControl([]),
      storeCategoryId: new FormControl(),
      storeCategoryItemCode: new FormControl(),
    })
  }


  changeShouldEnter() {
    if (this.form.get('shouldEnter').value[0]) {
      this.form.get("storeCategoryId").addValidators(Validators.required)
      this.form.get("storeCategoryItemCode").addValidators(Validators.required)
    } else {
      this.form.get("storeCategoryId").removeValidators(Validators.required)
      this.form.get("storeCategoryItemCode").removeValidators(Validators.required)
    }
    this.cdr.detectChanges();
  }

我什至尝试过这种方式,但最终,当我登录表单时,它仍然无效,而且在该表单的控件内,它再次显示

require: true

.removeValidators([Validators.required])
//or
.addValidators([])
angular typescript angular-reactive-forms
1个回答
1
投票

添加或删除验证器时,请确保调用

updateValueAndValidity
,以使更改得到反映。

来自文档:

重新计算控件的值和验证状态。

默认情况下,它还会更新其祖先的值和有效性。

  changeShouldEnter() {
    const shouldEnterCtrl = this.form.get('shouldEnter');
    const storeCategoryIdCtrl = this.form.get('storeCategoryId');
    const storeCategoryItemCodeCtrl = this.form.get('storeCategoryItemCode');
    if (shouldEnterCtrl?.value?.[0]) {
      storeCategoryIdCtrl.addValidators(Validators.required)
      storeCategoryItemCodeCtrl.addValidators(Validators.required)
    } else {
      storeCategoryIdCtrl.removeValidators(Validators.required)
      storeCategoryItemCodeCtrl.removeValidators(Validators.required)
    }
    storeCategoryIdCtrl.updateValueAndValidity(); // <- changed here!
    storeCategoryItemCodeCtrl.updateValueAndValidity(); // <- changed here!
  }
© www.soinside.com 2019 - 2024. All rights reserved.