反应式表单 - 禁用属性 [英] Reactive forms - disabled attribute

查看:35
本文介绍了反应式表单 - 禁用属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 formControl 中的 disabled 属性.当我把它放在模板中时,它起作用了:

I am trying to use the disabled attribute from a formControl. When I put it in the template, it works:

<md-input formControlName="id" placeholder="ID" [disabled]="true"></md-input>

但是浏览器提醒我:

看起来您正在使用具有反应形式的 disabled 属性指示.如果您将禁用设置为 true当你在组件类中设置这个控件时,disabled 属性实际上会在 DOM 中设置为你.我们建议使用这种方法来避免检查后更改"错误.

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)
  });

所以我把它放在FormControl中,并从模​​板中删除:

So I put it in the FormControl, and deleted from the template:

constructor(private itemsService: ItemsService) {
    this._items = [];
    this.myForm = new FormGroup({
        id: new FormControl({value: '', disabled: true}, Validators.required),
        title: new FormControl(),
        description: new FormControl()
    });
    this.id = this.myForm.controls['id'];
    this.title = this.myForm.controls['title'];
    this.description = this.myForm.controls['description'];
    this.id.patchValue(this._items.length);
}

但它不起作用(它没有禁用input).有什么问题?

But it does not work (it is not disabling the input). What is the problem?

推荐答案

我一直在使用 [attr.disabled] 因为我仍然喜欢这个模板驱动而不是程序化的 enable()/disable() 作为这是优越的海事组织.

I have been using [attr.disabled] because I still like this template driven than programmatic enable()/disable() as it is superior IMO.

改变

<md-input formControlName="id" placeholder="ID" [disabled]="true"></md-input>

<md-input formControlName="id" placeholder="ID" [attr.disabled]="true"></md-input>

如果您使用较新的材料,请将 md-input 更改为 mat-input.

If you are on newer material change md-input to mat-input.

这篇关于反应式表单 - 禁用属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆