如何正确使用HostListener装饰器来调用超类函数?

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

我正在努力根据official Angular styleguide用HostListener和HostBinding替换主机元数据。起点如下:我有一个从ng bootstrap superclass ngCheckBox继承的自定义指令。在使用主机元数据的旧拼写中,一切都很顺利。但是如果我现在尝试切换到新的最佳实践,我会收到错误消息:

Cannot read property 'target' of undefined
    at CustomCheckBoxDirective.NgbCheckBox.onInputChange

我怀疑我错误地使用了装饰器HostListener。

如何正确使用HostListener来访问超类函数?


具有主机元数据的CustomDirective:

@Directive({
  selector: '[customButton][type=checkbox]',
  host: {        
    '(change)': 'onInputChange($event)'        
  },
  providers: [CUSTOM_CHECKBOX_CONTROL_VALUE_ACCESSOR]
})
export class CustomCheckBoxDirective extends NgbCheckBox {
  constructor(private myLabel: CustomButtonLabelDirective) {
    super(myLabel);
  }
} 

使用HostBinding / HostListener的CustomDirective:

@Directive({
  selector: '[customButton][type=checkbox]',
  providers: [CUSTOM_CHECKBOX_CONTROL_VALUE_ACCESSOR]
})
export class CustomCheckBoxDirective extends NgbCheckBox {      
  @HostListener('change') changeListener($event: any) {
    this.onInputChange($event);
  }      


  constructor(private myLabel: CustomButtonLabelDirective) {
    super(myLabel);
  }

NgbCheckBox超类:

export declare class NgbCheckBox implements ControlValueAccessor {       
    // ...
    onInputChange($event: any): void;
    // ...
}
javascript angular
1个回答
2
投票

你必须告诉angular传递这样的事件对象,否则,没有传递任何东西,这意味着你的参数假定undefined为其值

@HostListener('change', ['$event'])
changeListener(event: any) {
    this.onInputChange(event);
} 
© www.soinside.com 2019 - 2024. All rights reserved.