无法读取未定义的属性'disable':在Ivy中未定义this.ngControl.control

问题描述 投票:1回答:2

就像this issue states,如果您尝试使用指令访问ngControl.control:

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

  constructor(private ngControl: NgControl) {}
}

第一次渲染时会出现错误:

core.js:5828 ERROR TypeError: Cannot read property 'disable' of undefined
angular angular9 angular-ivy
2个回答
0
投票
给定链接中的解决方案很不可靠,也不可靠。

直到他们解决问题,在第一个渲染中仅使用if-s来保护表达式:

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 .:注意新的safe / elvis运算符,您也可以在Angular 9的TS代码中使用它:)

© www.soinside.com 2019 - 2024. All rights reserved.