angular - 在 Angular 验证器中链接两个字段
问题描述
我有一个 Angular 9 表单,其中四个字段相关。一个是复选框,其余的是输入。当复选框被选中时,输入不应该是空的,但是当它没有被选中时,没有关系。我想为此制作验证器,以便仅当字段为空且第一个字段设置为 true 时才会出现错误。
我还考虑过创建一个表示复选标记状态的本地布尔值,然后像这样将其传递给验证器。
export function linkedFieldValidator(toggler: boolean): ValidatorFn {
console.log('updated');
return (control: AbstractControl): {[key: string]: any} | null => {
return (toggler && control.value === '') ? {linkedField: {value: control.value}} : null;
};
}
...
field: new FormControl('', linkedFieldValidator(this.checkboxvalue)),
...
但是,我想这不起作用,因为它只传递布尔值一次并且之后不会更新。即使调用updateValueAndValidity()
也不起作用,这对我来说很奇怪(如果不是这样,那么它的目的是什么?)。
我的结构FormGroup
看起来像这样:
this.form = this.formBuilder.group({
name: new FormControl(''), // don't care
address: new FormControl(''), // don't care
car: new FormControl(false), // do care - this is the checkmark
license_plate: new FormControl('', Validators.pattern(MY_LICENSE_PLATE_REGEX)), // shouldn't be empty when car
mileage: new FormControl('') // shouldn't be empty when car
hair: new FormControl(false), // do care - this is the checkmark
hair_color: new FormControl(''), // shouldn't be empty when hair
});
如您所见,我有几个FormControll
s 相互连接,我只想将其中几个链接起来。另一个需要注意的重要事项是,虽然如果违反其中一个条件,整个表单可能会无效,但我希望能够单独解决每个错误,以便我可以在适当的位置显示适当的消息。
我没有更多的想法,有人可以帮助我吗?我正在使用反应形式。
解决方案
问题是您只将初始值传递给linkFieldValidator
函数。
为了动态获得值,您可以通过 传递linkFieldValidator
,FormGroup
如下所示:
readonly formGroup = this.formBuilder.group(
{
checkbox: '',
name: ''
},
{ validator: linkedFieldValidator }
);
完整样本:
import { ChangeDetectionStrategy, Component } from '@angular/core';
import {
AbstractControl,
FormBuilder,
FormGroup,
ValidationErrors,
ValidatorFn,
} from '@angular/forms';
export const linkedFieldValidator = (formGroup: FormGroup): ValidationErrors | null => {
const [checkboxFormControlValue, nameFormControlValue] = [
formGroup.get('checkbox')!.value,
formGroup.get('name')!.value
];
return checkboxFormControlValue && !nameFormControlValue
? { linkedField: { value: nameFormControlValue } }
: null;
};
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
selector: 'input-overview-example',
styleUrls: ['input-overview-example.css'],
templateUrl: 'input-overview-example.html'
})
export class InputOverviewExample {
readonly formGroup = this.formBuilder.group(
{
checkbox: '',
name: ''
},
{ validator: linkedFieldValidator }
);
constructor(private readonly formBuilder: FormBuilder) {}
}
编辑1:如果您需要将错误驻留在每个表单控件中,您可以将您的更改linkedFieldValidator
为:
export const linkedFieldValidator = (formGroup: FormGroup): null => {
const { value: checkboxFormControlValue } = formGroup.get('checkbox')!;
const inputFormControls = [
formGroup.get('input1')!,
formGroup.get('input2')!,
formGroup.get('input3')!,
];
inputFormControls.forEach(inputFormControl => {
const { value } = inputFormControl;
const errors = checkboxFormControlValue && !value ? { linkedField: { value } } : null;
inputFormControl.setErrors(errors);
});
return null;
};
请注意,如果您需要保留其他错误,您可能需要在之前进行一些处理setErrors
。
编辑 2:
对于可以拥有多个链接字段的通用方法,您可以执行以下操作:
type LinkedFormControl = Record<string, string | readonly string[]>;
const arrayify = <T>(itemOrItems: T | readonly T[]): readonly T[] => {
return Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];
};
const getErrorObjectSanitized = <T extends object>(obj: T): T | null => {
return Object.keys(obj).length === 0 ? null : obj;
};
const getErrorsFor = (
checkerValue: boolean,
formControl: FormControl,
): object | null => {
const { errors, value } = formControl;
const { error, ...oldErrors } = errors || {};
const processedErrors = {
...(checkerValue && !value ? { error: true } : {}),
...oldErrors,
};
return getErrorObjectSanitized(processedErrors);
};
export const linkedFieldValidator = (linkedFormControls: LinkedFormControl) => {
return (formGroup: FormGroup): ValidationErrors | null => {
Object.keys(linkedFormControls).forEach(key => {
const { value: checkerValue } = formGroup.get(key)!;
const dependentKeys = arrayify(linkedFormControls[key]);
dependentKeys
.map(dependentKey => formGroup.get(dependentKey)!)
.forEach((dependentFormControl: FormControl) => {
dependentFormControl.setErrors(
getErrorsFor(checkerValue, dependentFormControl),
);
});
});
return null;
};
};
...电话会是这样的:
{
validator: linkedFieldValidator({
car: ['license_plate', 'mileage'],
hair: 'hair_color',
}),
},
推荐阅读
- graphics - 如果可以使用网格属性,为什么要使用着色器?
- python-3.x - 有没有办法使用 pygad 模块执行多目标分析?
- android - Visual Studio 无法创建新的 Android 设备
- java - 如何在 Android 应用程序中使用 HttpURLConnection?
- rust - 如何提取给定字符之前的字符串前缀?
- java - 使用带有字符串的 findViewById 查找对象始终返回 null
- python - وصلى 字符在将网页抓取获得的文本写入 csv 文件时显示
- python - 使用模型的预测来训练新模型
- javascript - 如何在没有外部模块的情况下使用 nodejs 成功创建一个简单的表单
- c# - 无法将 ASP.NET Web API 发布到 Azure 应用服务