[英]Delete errors from one Form Field in Angular's Reactive Forms
使用 Angular 8 我有一个反应形式:
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
}
当form.value.income
没有价值时,我想删除与form.value.period
相关的任何错误并能够提交表单。
我怎样才能做到这一点?
也许你可以试试这样的somzthing?
ngOnInit() {
this.form.valueChanges().subscribe(({ income }) =>
if (income && income.length) {
this.form.get('period').setErrors(null);
}
);
}
我没有测试它,所以你可以走得更远。
好吧,我想我会试一试。
最佳实践是创建自定义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')
});
}
一个工作示例: https : //stackblitz.com/edit/angular-rd15bu
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.