Angular 表单控件禁用绑定不起作用

Angular form control disabled binding not working

我有一个在页面加载时禁用的表单控件。当用户单击按钮时,表单应该可以进行编辑。但是,当我切换禁用控件的 属性 时,什么也没有发生。

模板

<form [formGroup]='accountForm'>
  <md-input-container>
    <input mdInput formControlName='name' />
  </md-input-container>
  <button (click)='isEditing = !isEditing'>Edit</button>
</form>

组件

export class AccountComponent {
  private accountForm: FormGroup;
  private isEditing = false;
  private name: FormControl = new FormControl({ value: '', disabled: !isEditing; 

  constructor(
    formBuilder: FormBuilder
  ) {
    this.accountForm = formBuilder.group({
      'name': this.name
    });
  });
}

根据此处的文档:https://angular.io/api/forms/FormControl

You can also initialize the control with a form state object on instantiation, which includes both the value and whether or not the control is disabled.

所以设置这个:

private name: FormControl = new FormControl({ value: '', disabled: !isEditing;

仅设置控件的初始化方式。 绑定它,也不会随着 isEditing 值的变化而改变它。

查看此问题了解更多信息:https://github.com/angular/angular/issues/11271

(我刚刚意识到 link Pankaj Parkar 在他们的评论中提供的相同。)

问题出在您的模板中。

您的 formControlName 有错字。您有 formControlName="Name" 而不是 formControlName="name"。注意上限。

此外,isEditing 未绑定到您的表单控件对象。

如果你想根据 isEditing 值改变状态,那么你应该做如下的事情:

<form [formGroup]='accountForm'>
  <md-input-container>
    <input mdInput formControlName='name' />
  </md-input-container>
  <button (click)='toggleEditMode()'>Edit</button>
</form>

请注意对方法的调用。

export class AccountComponent {
  private accountForm: FormGroup;
  private isEditing = false;
  private name: FormControl = new FormControl({ value: '', disabled:true; 

  constructor(formBuilder: FormBuilder) {
    this.accountForm = formBuilder.group({
      'name': this.name
    });
   }

   toggleEditMode() {
      this.isEditing = !this.isEditing;
      if(this.isEditing){
         this.name.enable();
      }else{
         this.name.disable();
   }
}

您可以使用enable/disable方法来改变禁用状态

template.html

<button (click)="toggleDisable()">Edit</button>

component.ts

toggleDisable() {
  this.accountForm.get('name')[!this.isEditing ? 'enable' : 'disable']();
  this.isEditing = !this.isEditing;
}

Plunker Example