关于Angular2指令,我想使用outputs
而不是@Output
,因为我有很多自定义事件,并希望保持DRY。
但是,我有TypeError: Cannot read property 'subscribe' of undefined
,我不知道为什么会这样。
http://plnkr.co/edit/SFL9fo?p=preview
import { Directive } from "@angular/core";
@Directive({
selector: '[my-directive]',
outputs: ['myEvent']
})
export class MyDirective {
constructor() {
console.log('>>>>>>>>> this.myEvent', this.myEvent);
}
}
这是使用此指令的应用程序组件
答案 0 :(得分:28)
您需要初始化输出:
import { Directive } from "@angular/core";
@Directive({
selector: '[my-directive]',
outputs: ['myEvent']
})
export class MyDirective {
myEvent:EventEmitter<any> = new EventEmitter(); // <-----
constructor() {
console.log('>>>>>>>>> this.myEvent', this.myEvent);
}
}
您还可以使用@HostListener
装饰器:
@Directive({
selector: '[my-directive]'
})
export class MyDirective {
@HostListener('myEvent')
myEvent:EventEmitter<any> = new EventEmitter(); // <-----
constructor() {
console.log('>>>>>>>>> this.myEvent', this.myEvent);
}
}