angular-reactive-formsangular-directiveangular9angular-ivy

Angular 9 Ivy, NgControl not initialized in Directive


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 an open issue you can find Angular Issues

    There is a nice solution that tweet by Alexey Zuev

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

    Here is an example of 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