Home > other >  Angular - dynamically disable input with getter on Reactive Forms?
Angular - dynamically disable input with getter on Reactive Forms?

Time:12-06

I have the following control on my Angular reactive form:

name: this.name = this.fb.control({ value: '', disabled: this.isNameDisabled }, this.nameValidations )

isNameDisabled is a getter as following:

private get isNameDisabled(): boolean {
    return this.isDisabled;
}

The first load works correctly, but when updating this.isDisabled to True, disabled property is not updated to true, and the input is still enabled.

Is there any way to dynamically disable the input without using this.name.disable()?

CodePudding user response:

In this case name: this.name = this.fb.control({ value: '', disabled: this.isNameDisabled }, this.nameValidations ) will work only to initial behavior, if you change the value of this.isNameDisabled will no reflect to the control.

To what you need the best approach is this.form.controls['name'].disable();

CodePudding user response:

what is the problem with calling this.name.disable() ?

You could use a directive:

import { NgControl } from '@angular/forms';

@Directive({
  selector: '[customDisable]'
})
export class CustomDisableDirective {

  @Input() set customDisable( isDisabled: boolean ) {
    const action = isDisabled ? 'disable' : 'enable';
    this.ngControl.control[action]();
  }

  constructor( private ngControl : NgControl ) {
  }

}

Then use it inside your HTML:

<input [formControl]="formControl" [customDisable]="isNameDisabled()">

CodePudding user response:

You can also do it in template by assigning a variable to a disabled attribute. In that case you'd have a method which sets disabled variable like so:

isNameDisabled = false;

ngOnInit(){
  this.setNameDisabled();
}

setNameDisabled() {
  // this is just an example, you should replace it with any logic that you have
  this.isNameDisabled = true;
}

And template should look as following:

<input [formControl]="formControl" [attr.disabled]="isNameDisabled">
  • Related