Angular 9 Ivy, NgControl not initialized in Directive

Issue

I’m attempting to update my project to Angular9 / Ivy and face following problem.
I have a custom “disabledControl” directive, as described in the following Blog (https://netbasal.com/disabling-form-controls-when-working-with-reactive-forms-in-angular-549dd7b42110). I’m using it in a reactive form with an expression to enable / disable specific controls based on a combination of checkboxes.
Since the update to Angular9 / Ivy, ngControl.control is not set anymore when the @Input method set disableControl is first called.
Any hints how we can fix the proposed blog solution?

Solution

There is open issue you can found Angular Issues

There is a nice solution that twit by Alexey Zuev

The solution is to use the ngOnChanges lifecycle hook with your directive.

Here is an example how to use the ngOnChanges lifecycle hook in order to fix the issue.

import { NgControl } from '@angular/forms';
import { Directive, Input, OnChanges } from '@angular/core';

@Directive({
  selector: '[disableControl]',
})
export class DisableControlDirective implements OnChanges {
  @Input('disableControl') disableControl;
  constructor(private ngControl: NgControl) {}

  ngOnChanges(changes) {
    if (changes['disableControl']) {
      const action = this.disableControl ? 'disable' : 'enable';

      this.ngControl.control[action]();
    }
  }
}

The full example by Alexey Zuev

Answered By – ofir fridman

Answer Checked By – Willingham (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.