Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 246
ForestG Avatar asked Feb 20 '20 09:02

ForestG


1 Answers

The solution in the given link is quite hacky and unreliable.

Until they fix the issue, simply guard the expression with if-s for the first rendering:

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

  constructor(private ngControl: NgControl) {}
}

ps.: notice the new safe/elvis operator which you can use in Angular 9 in the TS code too :)

like image 144
ForestG Avatar answered Oct 16 '22 20:10

ForestG