For*_*stG 5 angular angular-ivy angular9
正如此问题所述,如果您尝试使用指令访问 ngControl.control:
export class DisabledDirective {
@Input()
set opDisabled(condition: boolean) {
const action = condition ? 'disable' : 'enable';
this.ngControl.control[action]();
}
constructor(private ngControl: NgControl) {}
}
Run Code Online (Sandbox Code Playgroud)
第一次渲染时会出现错误:
core.js:5828 ERROR TypeError: Cannot read property 'disable' of undefined
Run Code Online (Sandbox Code Playgroud)
给定链接中的解决方案非常笨拙且不可靠。
在他们解决问题之前,只需在第一次渲染时使用 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) {}
}
Run Code Online (Sandbox Code Playgroud)
ps.:注意你也可以在 TS 代码中的 Angular 9 中使用新的 safe/elvis 运算符:)