'Cannot read property 'disable' of undefined: this.ngControl.control is undefined in Ivy

Just as this issue states, if you try to access an ngControl.control with a Directive:

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

  constructor(private ngControl: NgControl) {}
}

You will reach an error upon first rendering:

core.js:5828 ERROR TypeError: Cannot read property 'disable' of undefined


Solution 1:[1]

The solution is use the OnChanges lifecycle (as it's mentioned in the official issue)

@Directive({ selector: '([formControlName], [formControl])[disableControl]' })
export class DisableControlDirective implements OnChanges {
  @Input() disableControl = false;

  ngOnChanges(changes: SimpleChanges) {
    if (changes.disableControl) {
      this.ngControl.control?.disable();
    } else {
      this.ngControl.control?.enable();
    }
  }

  constructor(private ngControl: NgControl) {}
}

The usage will be like

<input formControlName="id" [disableControl]="true" />

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mikael Boff