【问题标题】:Cannot read property 'disable' of undefined: this.ngControl.control is undefined in Ivy无法读取未定义的属性“禁用”:this.ngControl.control 在 Ivy 中未定义
【发布时间】:2020-02-20 09:48:47
【问题描述】:

就像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


    【解决方案1】:

    给定链接中的解决方案非常老套且不可靠。

    在他们解决问题之前,只需在第一次渲染时使用 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.:请注意新的安全/elvis 运算符,您也可以在 TS 代码中的 Angular 9 中使用它:)

    【讨论】:

    • 这个问题已经在 Angular 的 github 项目中提出了吗?
    【解决方案2】:

    解决方案是使用 OnChanges 生命周期(正如官方问题中提到的那样)

    @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) {}
    }
    

    用法会是这样的

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-17
      • 2020-11-29
      • 1970-01-01
      • 1970-01-01
      • 2020-04-06
      • 2016-01-10
      • 1970-01-01
      相关资源
      最近更新 更多