首页 > 解决方案 > 如何避免使用“禁用”属性来启用/禁用基于 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: ['']
        });

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

[disabled] 非常适合这个,buuuuuut ......我们得到了那个信息。

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

但是,如果这是一件事,我似乎找不到它的语法。而且,我所见过的 SO 和其他地方的其他热门歌曲并没有真正提供非常干净的方式来绕过这条消息(我尝试将 [disabled] 交换为 [attr.disabled],但这只是直截了当没用......也许Angular 9已经弃用了,我不知道)。

那么,有谁知道如何订阅响应式 FromGroup 的验证状态?或者,有没有更好的方法来启用/禁用基于这种反应表单的验证状态的控件?

谢谢!

标签: angularangular-reactive-formsangular-validation

解决方案


尝试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>

推荐阅读