updateValueAndValidity 不适用于特定的 formControl

问题描述

我动态添加表单控件后,输入为rrp.invalidtouched不起作用。如果我写了一些东西并将其删除,它会起作用。

最初,它运行良好,但是当我删除 rrp 表单控件并动态添加它时,它没有按预期运行

组件 ts 文件

ngOnInit() {
    this.form = this.fb.group({
        rrp: ['',[Validators.required]],priceType: [PricingType.Fixed,[]],});

    this.form.get('priceType').valueChanges.pipe(
        takeuntil(this.unsubscribe),debounceTime(500)
    ).subscribe((chosenPriceType) => {
        this.managePricingControls(chosenPriceType);
    });
}

private managePricingControls(priceType: string) {
    switch(priceType) {
        case PricingType.Fixed:
            this.addFixedPriceControls();
            break;
        case PricingType.Subscription:
            this.removeFixedPriceControls();
            break;
        default:
            break;
    }
}

private addFixedPriceControls() {
    this.form.addControl(
        'rrp',this.fb.control(0,Validators.required)
    );
    this.form.get('rrp').updateValueAndValidity()
    this.form.addControl(
        'expiresInMonth',this.fb.control(0)
    );
}

get rrp() {
    return this.form.get('rrp');
}

模板

<div *ngIf="rrp" class="form-group required">

  <label for="rrp" title="Recommended Retail Price">RRP</label>
  <input
    type="text"
    class="form-control "
    id="rrp"
    formControlName="rrp"
    appPositiveNumber
    [decimal]="true"
    [decimalNumbers]="2"
    autocomplete="off"
  >
  <span class="currency">{{currency}}</span>

  <div *ngIf="rrp?.invalid && (rrp?.dirty || rrp?.touched)" class="alert alert-danger">
    Recommended Retail Price is required
  </div>

</div>

注意:我也尝试将 setTimeout(() => this.form.get('rrp').updateValueAndValidity(),0); 放在

解决方法

所以,解决方案是我以错误的方式通过了验证。而不是

this.form.addControl(
  'rrp',this.fb.control('',Validators.required)
);

我应该添加如下控件:

this.form.addControl(
  'rrp',[Validators.required])
);

Validators.required 作为数组元素。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...