我有这个表单组:
this.fb.group({
a: ["", Validators.required],
b: ["", Validators.required],
c: [{value: "", disabled: true}, Validators.required]
});
在模板中,填充前2个控件(a和b),在valueChanges.subscribe()方法中为第三个控件(c)生成值。
在表单下方,我有一个用于下一页的按钮。这应该被禁用,直到表单有效(3 个控件不为空),但现在它不能按我的意愿工作,因为第三个控件被禁用,因此跳过该字段的验证。 结果是,第二个控件填满后,即使我的生成功能失败,控件“c”保持为空,按钮也是启用的。
我在其他帖子中看到了 [attr.disabled] 的用法,但在 Angular 15 中它似乎不起作用。是否有另一种方法可以禁用模板中的字段以保持验证运行?
我正在尝试找到一种不同于将字段错误设置到生成函数中的解决方案。
这看起来像是一个错误,请参阅 github 中的讨论
但是您可以使用指令作为临时解决方案
//I use "disable" as selector instead of disabled
@Directive({
selector: '[disable]',
standalone:true
})
export class CustomDisabledDirective implements AfterViewInit {
_disable:boolean
@Input('disable') set _(value:boolean)
{
this._disable=value;
this.ngAfterViewInit();
}
constructor(private elementRef:ElementRef) { }
ngAfterViewInit()
{
if (this._disable)
this.elementRef.nativeElement.setAttribute('disabled','true')
else
this.elementRef.nativeElement.removeAttribute('disabled')
}