gpt4 book ai didi

javascript - Angular 7 中的动态验证 : enable() & setValidators depending on flags triggered by changes

转载 作者:行者123 更新时间:2023-11-30 19:50:34 24 4
gpt4 key购买 nike

我上一个 Angular 项目是很久以前的事了,同时我也在使用 VueJS。现在我回来了,并在 Angular 7 中实现了一个带有一些条件字段的响应式(Reactive)表单。

我下面的解决方案有效,我可以根据标志启用字段或设置验证器。但不知何故我不喜欢这个解决方案,它太长而且不直观。没有人能凭直觉知道,您必须禁用一个字段才能禁用验证器。 Angular/TypeScript 专家可以帮助我优化代码或以正确的方式执行吗?

onChangeType(scope: string) {
console.log(scope);
this.myForm.get('riskType').disable();
this.myForm.get('chancheType').disable();

if (scope === 'local') {
this.flags.isScopeLocal = true;
this.flags.isScopeTemplate = false;
this.flags.isScopeGlobal = false;
this.myForm.get('chancheType').enable();
this.myForm.get('chancheType').setValidators(Validators.required);
} else if (scope === 'template') {
this.flags.isScopeTemplate = true;
this.flags.isScopeLocal = false;
this.flags.isScopeGlobal = false;
this.myForm.get('riskType').enable();
this.myForm.get('riskType').setValidators(Validators.required);
} else {
// global
this.flags.isScopeLocal = false;
this.flags.isScopeTemplate = false;
this.flags.isScopeGlobal = true;
this.myForm.get('riskType').disable();
this.myForm.get('chancheType').disable();
}
}

简短解释:如果作用域是本地的或模板的,将有一个新的必填字段。如果范围是全局的,那么这个字段就会消失,它的验证器将被停用。

最佳答案

使用指令补充我的评论 How to make a disabled reactive form Editable in Angular2

孤独,您不需要使用 setValidators 更改验证器,指令是谁启用/禁用控件。我认为更“可读”

<input formControlName="riskType" [enabledControl]="scope=='local'">
<input formControlName="chancheType" [enabledControl]="scope=='template'">

myForm=this.fb.group({
riskType:['',Validators.required],
cacheType:['',Validators.required],

})

关于javascript - Angular 7 中的动态验证 : enable() & setValidators depending on flags triggered by changes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54517613/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com