efarley
efarley

Reputation: 8661

Angular form control disabled binding not working

I have a form control that I disable when the page loads. When the user clicks a button the forms should become enabled for editing. However when I toggle the property that disabled the control nothing happens.

Template

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

Component

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

Upvotes: 5

Views: 40204

Answers (3)

Gr&#233;gory Elhaimer
Gr&#233;gory Elhaimer

Reputation: 2801

The problem is in your template.

You have a typo on formControlName. You have formControlName="Name" instead of formControlName="name". Notice the caps.

Moreover, isEditing is not bound to your form control object.

If you want to change the state according to isEditing value, then you should do something like following:

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

Note the call to a method instead.

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

Upvotes: 0

yurzui
yurzui

Reputation: 214057

You can use enable/disable methods to change disable state

template.html

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

component.ts

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

Plunker Example

Upvotes: 10

DeborahK
DeborahK

Reputation: 60518

According to the docs here: 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.

So setting this:

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

Is only setting how the control is initialized. It is not binding it nor changing it as the value of isEditing changes.

See this issue for more information: https://github.com/angular/angular/issues/11271

(Which I just realized is the same link that Pankaj Parkar provided in their comments.)

Upvotes: 12

Related Questions