如何避免使用“ disabled”属性基于FormGroup的验证状态来启用/禁用Angular反应表单控件?

问题描述

我正在一个Angular 9项目的团队中工作,该项目的许多组件都使用响应式表单,我的任务是重构一些代码,以保留现有功能,但从开发者控制台中消除此烦人的消息:

 It looks like you're using the disabled attribute with a reactive form directive. If you set disabled to true
      when you set up this control in your component class,the disabled attribute will actually be set in the DOM for
      you. We recommend using this approach to avoid 'changed after checked' errors.
       
      Example: 
      form = new FormGroup({
        first: new FormControl({value: 'Nancy',disabled: true},Validators.required),last: new FormControl('Drew',Validators.required)
      });

disabled属性当前仅在“保存”(提交)按钮html上使用,其设置如下(其中componentForm是在component.ts ngOnit中内置的FormGroup的名称):

<button class="btn btn-primary btn-sm" type="submit" [disabled]="!componentForm.dirty || !componentForm.valid"><i class="fa fa-save" aria-hidden="true"></i>Save
</button>

这是component.ts中表单组的设置(仅一个示例;应用程序中的多个组件使用相同的设置):

componentForm: FormGroup;

constructor(private fb: FormBuilder,//other stuff) {
        super();
    }

    ngOnInit(): void {
        
        this.componentForm = this.fb.group({
            title: ['',[Validators.required,Validators.maxLength(100)]],description: ['',[Validators.maxLength(500)]],program: ['',[Validators.maxLength(100)]],draftNumber: ['',[Validators.maxLength(100),Validators.pattern('^([zZ]-)([0-9][0-9][0-9][1-9])\\.([1-9][0-9][0-9]|[0-9][1-9][0-9]|[0-9][0-9][1-9]|[1-9]|0[1-9])')]],agencyRequestStatusName: ['']
        });

因此,我需要保留的功能是,只要未更改表单(原始)或无效表单(根据传递给formbuilder的验证器),就应该禁用“保存”按钮。

[disabled]为此非常有用,buuuuuut ...我们收到了该消息。

我想解决这个问题的直接想法是,好吧,也许我可以订阅一个Observable(也在ngOnit中使用),该对象可跟踪FormGroup(componentForm)的有效/无效状态,然后使用.disable()和每当Observable更改时,保存按钮上的.enable()方法

但是,如果这是一回事,我似乎找不到它的语法。而且,我见过的SO和其他地方上的其他热门歌曲也并没有提供解决此消息的非常干净的方法,(我尝试将[disabled]交换为[attr.disabled],但这只是直截了当没用...可能是Angular 9弃用的,我不知道)。

那么,有人知道如何订阅被动式FromGroup的验证状态吗?或者,是否有更好的方法来启用/禁用基于这种反应形式的验证状态的控件?

谢谢!

解决方法

尝试将attr.添加到您的禁用属性中,例如[attr.disabled]

<button class="btn btn-primary btn-sm" type="submit" [attr.disabled]="!componentForm.dirty || !componentForm.valid"><i class="fa fa-save" aria-hidden="true"></i>Save
</button>

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...