Disabling Form Controls When Working With Reactive Forms in Angular

Alex Onozor
alexonozor
Published in
2 min readJan 11, 2022

When working with Angular Reactive Forms there are times when you need to disable/enable a form control, for example:

<input [formControl]=”formControl” [disable]=”condition”>

If you’ve ever tried the above code, you probably have encountered the following warning.

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.

Angular tells you that it’s better for you to use the ways it gives you to disable/enable form controls.

You can enable/disable a form control by using the following ways:

  1. Instantiate a new FormControl with the disabled property set to true. FormControl({value: '', disabled: true}) .
  2. Calling control.disable() or control.enable() .

But sometimes you miss(😳) or need the method you’re used to (👆). Let’s create a directive that will help us recreate this functionality.

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

@Directive({
selector: '[disableControl]'
})
export class DisableControlDirective {

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

constructor( private ngControl : NgControl ) {
}

}

We can get a reference to the form control instance via DI. Then it is only a matter of calling the correct method according to the Input() value.

Now we can use our directive like this:

<input [formControl]=”formControl” [disableControl]=”disable”>
<button (click)=”disable = true”>Disable</button>
<button (click)=”disable = false”>Enable</button>

--

--

Alex Onozor
alexonozor

Software Consultant, JavaScriptor, Web evangelist. Open source contributor. Software Architect.