angular - Angular FormBuilder 组已弃用
问题描述
我看到有一个主题看起来像我的,但它并没有真正回答我的问题,因为我们没有以相同的方式管理错误。FormBuilder 组已弃用
首先,我刚刚迁移到 Angular 11,现在我遇到了这个问题:
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.
在这个页面中,我会在我的页面上自动生成许多表单,在日期范围的情况下,我使用两个日期选择器。我创建了一个函数来检查 2 个日期选择器中的值。
零件:
newGroup = this.fb.group(
{
[node.type + '_' + node.objectId + '_dateFrom']: [
'',
[Validators.required]
],
[node.type + '_' + node.objectId + '_dateTo']: [
'',
[Validators.required]
]
},
{
validator: CheckFromToDate(
node.type + '_' + node.objectId + '_dateFrom',
node.type + '_' + node.objectId + '_dateTo'
)
}
);
验证器:
export function CheckFromToDate(fromName: string, toName: string) {
return (formGroup: FormGroup) => {
const from = formGroup.controls[fromName];
const to = formGroup.controls[toName];
const dateFrom = new Date(from.value);
const dateTo = new Date(to.value);
const today = new Date();
if (to.errors && from.errors) {
// return if another validator has already found an error on the matchingControl
return;
}
if (!from.value) {
from.setErrors({ wrongDate: true });
to.setErrors(null);
} else if (!to.value) {
to.setErrors({ wrongDate: true });
from.setErrors(null);
} else if (dateFrom.getTime() < -3600000) {
from.setErrors({ wrongDate: true });
to.setErrors(null);
} else if (dateFrom > today) {
from.setErrors({ wrongDate: true });
to.setErrors(null);
} else if (dateTo.getTime() < -3600000) {
to.setErrors({ wrongDate: true });
from.setErrors(null);
} else if (dateTo > today) {
to.setErrors({ wrongDate: true });
from.setErrors(null);
} else if (dateFrom.getTime() > dateTo.getTime()) {
from.setErrors({ fromTo: true });
to.setErrors({ fromTo: true });
} else {
from.setErrors(null);
to.setErrors(null);
}
};
}
如何让我的验证器使用 Angular 11 中处理验证器的新方法?
解决方案
更改您的验证人签名
return (formGroup: FormGroup)
至
return (controls: AbstractControl)
然后更改您访问控件的方式
const from = formGroup.controls[fromName];
至
const from= controls.get(fromName);
还要更改您报告错误的方式
from.setErrors({ wrongDate: true });
至
return from.setErrors({ wrongDate: true }); // note the return statement.
最后一个改变是改变
newGroup = this.fb.group(
{
...
},
{
validator: CheckFromToDate(
node.type + '_' + node.objectId + '_dateFrom',
node.type + '_' + node.objectId + '_dateTo'
)
}
);
至
newGroup = this.fb.group(
{
...
},
{
validator: CheckFromToDate(
node.type + '_' + node.objectId + '_dateFrom',
node.type + '_' + node.objectId + '_dateTo'
)
} as AbstractControlOptions
);
请注意转换为AbstractControlOptions
并且应该删除已弃用的警告。
详细解释可以参考官方文档。
推荐阅读
- android - 当我将语言更改为法语时,getResources.getString(R.string.hello_world) 不起作用
- android - 此视图不受 android studio 约束
- html - TH 底部边框应显示一半。如何?
- docker - Docker 错误:服务器行为不端
- angularjs - 如何使用 angularjs 向 Paypal REST API 发出基于令牌的 GET 请求?
- java - Java中的Itree数据类型
- angularjs - 从 pdfmake 表中删除标题。
- javascript - 使用 jquery 切换当前类
- android - 使用异步任务在实时 Firebase 中提交大量值?
- php - 如何将无索引数组转换为索引数组