angular - Delete errors from one Form Field in Angular's Reactive Forms
问题描述
Using Angular 8 I have a Reactive form:
form: FormGroup;
submitting: boolean = false;
ngOnInit() {
this.form = this.formBuilder.group({
income: [''],
period: ['']
})
}
onSubmit() {
if (this.form.valid) {
this.submitting = true;
let model: Model = {
income: this.form.value.income,
period: this.form.value.period
}
// Remaining code
}
When form.value.income
has no value I would like to delete any errors associated with form.value.period
and be able to submit the form.
How can I do this?
解决方案
好吧,我想我会试一试。
最佳实践是创建一个自定义Validator
(在您自己的单独文件中进行分离),然后将其应用于Validator
全局formBuilder
validator
选项。
例子:
has-no-value.validator.ts:
import { FormGroup } from '@angular/forms';
export const hasNoValue = (controlName: string, matchingControlName: string) => {
return (formGroup: FormGroup) => {
const control = formGroup.controls[controlName];
const matchingControl = formGroup.controls[matchingControlName];
if (control.value === '') {
matchingControl.setErrors(null);
}
}
}
app.component.ts:
ngOnInit() {
this.form = this.formBuilder.group({
income: ['', [Validators.required]],
period: ['', [Validators.required]]
}, {
validator: hasNoValue('income', 'period')
});
}
推荐阅读
- asp.net - 在 WCF 服务应用程序中使用 Google 登录
- vtk - 如何在 python-vtk 中隐藏特定的演员
- apache-kafka - 一段时间后,Apache Kafka 服务器自动停止
- unit-testing - Kotlin 中的单元测试和高阶函数
- excel - Excel:如何使用前几个字符查找部分匹配项
- windows - FFmpeg 抛出数据包损坏错误,流超过 10Mbps
- c# - 使用 isDisplayed() 的 Selenium Webdriver 不起作用
- c# - 错误:OracleParameter 对象已包含在集合中
- python - 日期时间格式熊猫
- php - 在 EventSubscriber Symfony 3.4 上发送响应