Angular 2:禁用输入更改无效 [英] Angular 2: Disable input change not working

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

问题描述

 < input type =textformControlName = name[disabled] =!showName> 

动态禁用/启用表单输入。

从Rc7升级到2.0后,我在控制台窗口中看到以下警告:


<看起来你正在使用反应形式指令的disabled属性。如果在组件类中设置此控件时将disabled设置为true
,那么disabled属性实际上将设置在
you的DOM中。我们建议使用这种方法来避免'检查后更改'错误。

我已更改我的代码以遵循这些指示:

  this._userGroupUsersForm = this._formBuilder.group({
'users':[{'',disabled:this (Validator.required,Validators.minLength(3),Validators.maxLength(50),Validators.pattern(^ [a-zA-ZåäöÅÄÖ0-9 _-] + $)]) ]
});

这对于初始页面加载工作正常,但我无法再像以下那样切换状态:

  toggleName():void {th​​is.showName =!this.showName; } 

如何解决这个问题?

注意:我的老方法(通过设置[禁用])不再工作。

解决方案

这应该可以工作

  toggleName():void {
let ctrl = this.form.get('name')
ctrl.enabled? ctrl.disable():ctrl.enable()
}


Up until "final" 2.0 of Angular I have done this:

<input type="text" formControlName="name" [disabled]="!showName">

To dynamically disable/enable form inputs.

After upgrading from Rc7 to 2.0 I get this warning in the console window:

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.

I have changed my code to follow these instructions like this:

this._userGroupUsersForm = this._formBuilder.group({
        'users': [{'', disabled: this.showName}, Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(50), Validators.pattern("^[a-zA-ZåäöÅÄÖ 0-9_-]+$")])]
    });

And that works fine for the initial page load, but I can no longer toggle the status like this:

toggleName() : void { this.showName = !this.showName; }

How do I solve this?

Note: My "old" way of doing this (by setting [disabled]) doesn't work any more either.

解决方案

This should work

toggleName() : void { 
  let ctrl = this.form.get('name')
  ctrl.enabled ? ctrl.disable() : ctrl.enable()
}

这篇关于Angular 2:禁用输入更改无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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