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

查看:19
本文介绍了以正确的方式禁用 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.

谢谢

推荐答案

您可以将变量的分配更改为 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天全站免登陆