禁用Angular 5输入字段的正确方法 [英] Disable Angular 5 Input fields correct way

查看:106
本文介绍了禁用Angular 5输入字段的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样创建的FormGroup:

I have a FormGroup that was created like that:

form: FormGroup;

constructor(private _formBuilder: FormBuilder) { }

this.form = this._formBuilder.group({
  name: ['', Validators.required],
  email: ['', Validators.required, Validators.email]
});

当事件发生时,我想禁用这些输入,因此,在我添加的HTML中:

When an event occurs I want to disable those inputs, so, in the HTML I added:

<input class="form-control" placeholder="Name" name="name" formControlName="name" [(ngModel)]="name" autocomplete="off" [disabled]="isDisabled" required>

<input class="form-control" placeholder="Email" name="email" formControlName="email" [(ngModel)]="email" email="true" autocomplete="off" [disabled]="isDisabled" required>

其中isDisabled是变量,当发生上述事件时,我会切换到true.

可以想象,我收到消息:

Where isDisabled is a variable I toggle to true when the said event happens.

As you can imagine, I get the message:

您似乎正在使用带有反应形式的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)
  });

因此,在显示此警告的示例中,并进行了一些搜索,我发现我应该声明以下控件:

So, with the example this warning shows and with a little search I found that I should declare my controls like:

name: [{ value: '', disabled: this.isDisabled }, Validators.required]

问题是:当变量在true/false

之间更改时,它不会在禁用/启用之间切换 用变量控制输入是启用还是禁用的正确方法是什么?

The problem is: It is not toggling between disabled/enabled when the variable changes between true/false

How is the correct way of having a variable controlling if an input is enabled or disabled?

我不想手动执行该操作(例如:this.form.controls['name'].disable()),因为这似乎不是一种非常被动的方法,因此我必须在大量方法中调用它.可能不是一个好习惯.

I don't want to do it manually (ex: this.form.controls['name'].disable()) because it doesn't seems a very reactive way, I would have to call it inside a good amount of methods. Probably not a good practice.

Thx

推荐答案

您可以将变量的分配更改为setter方法,这样您就可以:

You can change the assignment of the variable to a setter method so that you'd have:

set isDisabled(value: boolean) {
 this._isDisabled = value;
 if(value) {
  this.form.controls['name'].disable();
 } else {
    this.form.controls['name'].enable();
  }
}

这篇关于禁用Angular 5输入字段的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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