问题描述
我动态添加表单控件后,输入为rrp.invalid
时touched
不起作用。如果我写了一些东西并将其删除,它会起作用。
最初,它运行良好,但是当我删除 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
作为数组元素。