angular - 表单更新后,反应式表单验证未在 UI 上更新
问题描述
我正在将表单从 Parent 传递给 chld 组件。所有验证都在父组件中完成,子组件只是渲染它。但是,我的表单中有一个名为 country 的字段,如果更新,它将获取一组新的验证规则。问题是,在我单击该字段之前,错误消息不会更新。我希望错误消息也能动态更新。下面是我的代码。父组件.ts:
this.addressForm
.get('city')
.setValidators([
Validators.maxLength(this.labelStateService.recipientValidation.city.maxLength),
Validators.pattern(this.labelStateService.recipientValidation.city.validationRegex),
this.labelStateService.recipientValidation.city.required ? Validators.required : Validators.nullValidator,
]);
this.addressForm
.get('contact')
.get('fullName')
.setValidators([
Validators.maxLength(this.labelStateService.recipientValidation.fullName.maxLength),
this.labelStateService.recipientValidation.fullName.required ?
Validators.required : Validators.nullValidator,
]);
父组件.html:
<app-address-box [addressForm]="addressForm"></app-address-box>
子组件.html
<form [formGroup]="addressForm">
<div class="form-floating-labels">
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<select name="isoCountry" (change)="onCountryChange()" class="form-control" formControlName="isoCountry" [ngClass]="{
'is-invalid':
addressForm.get('addressForm').get('isoCountry').invalid &&
(addressForm.get('addressForm').get('isoCountry').touched || submitted)
}">
<option *ngFor="let country of countries" [value]="country.alpha2Code">{{ country.shortName }} </option>
</select>
<label l10nTranslate for="isoCountry">ADDRESS.COUNTRY</label>
<p class="invalid-feedback">Enter a name.</p>
</div>
</div>
因此,在更新此字段时,我希望自动更新此 formGroup 的其他字段的错误消息。
请帮忙!!
解决方案
您需要再添加 2 行代码才能正常工作。请参考这个:
this.addressForm
.get('city')
.setValidators([
Validators.maxLength(this.labelStateService.recipientValidation.city.maxLength),
Validators.pattern(this.labelStateService.recipientValidation.city.validationRegex),
this.labelStateService.recipientValidation.city.required ? Validators.required : Validators.nullValidator,
]);
this.addressForm
.get('contact')
.get('fullName')
.setValidators([
Validators.maxLength(this.labelStateService.recipientValidation.fullName.maxLength),
this.labelStateService.recipientValidation.fullName.required ?
Validators.required : Validators.nullValidator,
]);
// Add these two lines
this.addressForm.get('city').updateValueAndValidity();
this.addressForm.get('contact').get('fullName').updateValueAndValidity();
推荐阅读
- php - Laravel 5.5 多数据库连接
- python-3.x - 为什么 `importlib.resources` 需要 `__init__.py`?
- html - 如何居中和叠加图像(在流式网络摄像头之上)
- c - 你如何在c中模128位支柱?
- python - 使用 python 删除@mentions、urls 和 # 符号
- swift - 使用 CommonCrypto 进行 AES 解密 - 缺少某些字符
- php - 如何使用mysql在php中将行更改为cloumn
- java - 如何解决有关 getSupportFragmentManager() 的错误?
- html - HTML 下载代码不会让我下载
- aws-lambda - Lambda 与 DynamoDB 在具有超过 500000 个不同值的表分区键上触发