angulartypescriptangular-materialangular-reactive-formsangular16

Angular 16 Reactive Form - Form Control disabled not working


I am making a reactive form with Angular 16. When the checkbox is checked, I want to prevent data entry to one of the inputs, that is, disable it. My code is as follows, but it doesn't work, can you help me? When I remove the formControlName, it becomes disabled, but then I cannot receive the entered data.

<form [formGroup]="personelForm">
  <div class="row">
    <mat-checkbox class="example-margin" formControlName="isCheck">Not Phone</mat-checkbox> <br>
  </div>

  <div class="row">

    <mat-form-field style="margin-right: 10px;">
      <mat-label>Phone</mat-label>
      <input matInput type="number" formControlName="phone" 
        [disabled]="personelForm.get('isCheck').value">
    </mat-form-field>


    <mat-form-field style=" margin-right: 10px;">
      <mat-label>Name</mat-label>
      <input matInput type="text" formControlName="name">
    </mat-form-field>

    <mat-form-field style="margin-right: 10px;">
      <mat-label>Surname</mat-label>
      <input matInput type="text" formControlName="surname" >
    </mat-form-field>

  </div>

</form>
personelForm: FormGroup;

constructor(private fb: FormBuilder){}
reloadForm() {
  this.personelForm = this.fb.group({
    isCheck:  new FormControl(false),
    phone: new FormControl(0),
    name:  new FormControl(''),
    surname:  new FormControl('')
  });
}

ngOnInit() {
  this.reloadForm();
}

Solution

  • Use [attr.disabled] (Attribute binding) instead of [disabled].

     <input
      matInput
      type="number"
      formControlName="phone"
      [attr.disabled]="personelForm.get('isCheck')!.value"
    />
    

    Alternatively, you can subscribe to the isCheck control's valueChanges observable and enable/disable the phone control in the component.

    this.personelForm.get('isCheck')!.valueChanges.subscribe((isCheck) => {
      if (isCheck) this.personelForm.get('phone')!.disable();
      else this.personelForm.get('phone')!.enable();
    });
    

    Demo @ StackBliz