【发布时间】:2021-03-17 04:40:15
【问题描述】:
我将我的项目迁移到 Angular 11,我注意到我添加的全局验证使 FormBuilder.group 不推荐使用以下消息:
group is deprecated: This api is not typesafe and can result in issues with Closure Compiler renaming.
Use the `FormBuilder#group` overload with `AbstractControlOptions` instead.
所以不推荐使用:
ingredientForm = this.fb.group({
ingredientType: ['', Validators.required],
ingredientFlavor: [''],
isMultiFlavor: [''],
ingredientBrand: [''],
ingredientName: [''],
imageFile: ['']
}, {validators: [ValidateThirdNumber.validate]});
如果没有 validators 选项,则不是。
我的ValidateThirdNumber 验证器:
class ValidateThirdNumber {
static validate(control: AbstractControl): void {
if (control) {
const isMultiFlavor = control.get('isMultiFlavor')?.value;
const ingredientFlavor = control.get('ingredientFlavor')?.value;
const ingredientBrand = control.get('ingredientBrand')?.value;
const ingredientName = control.get('ingredientName')?.value;
if (isMultiFlavor && ingredientFlavor.trim().length === 0) {
control.get('ingredientFlavor')?.setErrors({required_if: true});
} else {
control.get('ingredientFlavor')?.setErrors(null);
}
if (!ingredientFlavor && !ingredientBrand && !ingredientName) {
control.get('ingredientName')?.setErrors({required_at_least: true});
control.get('ingredientFlavor')?.setErrors({required_at_least: true});
control.get('ingredientBrand')?.setErrors({required_at_least: true});
} else {
control.get('ingredientName')?.setErrors(null);
control.get('ingredientFlavor')?.setErrors(null);
control.get('ingredientBrand')?.setErrors(null);
}
if (ingredientBrand && ingredientName && ingredientName === ingredientBrand) {
control.get('ingredientName')?.setErrors({not_the_same: true});
control.get('ingredientBrand')?.setErrors({not_the_same: true});
}
}
}
}
如何使用 AbstractControlOptions 重载它?
【问题讨论】:
-
我认为您可以在解释弃用的部分中找到解决方案:angular.io/api/forms/FormBuilder
-
@Ploppy 我在发布这个问题之前阅读了文档,不幸的是没有太大帮助,不知道该怎么做
标签: angular typescript angular-validation angular2-formbuilder