问题描述
限时送ChatGPT账号..关于 Angular2 指令,我想使用 outputs
而不是 @Output
因为我有很多自定义事件并希望保持 DRY.
但是,我遇到了TypeError: Cannot read property 'subscribe' of undefined
,我不知道为什么会这样.
这是使用该指令的应用组件
解决方案需要初始化输出:
import { Directive } from "@angular/core";@指示({选择器:'[我的指令]',输出:['myEvent']})导出类 MyDirective {myEvent:EventEmitter= new EventEmitter();//<----构造函数(){console.log('>>>>>>>>> this.myEvent', this.myEvent);}}
你也可以使用 @HostListener
装饰器:
@Directive({选择器:'[我的指令]'})导出类 MyDirective {@HostListener('myEvent')myEvent:EventEmitter= new EventEmitter();//<-----构造函数(){console.log('>>>>>>>>> this.myEvent', this.myEvent);}}
Regarding Angular2 directive, I wanted to use outputs
instead of using @Output
because I have many custom events and wanted to keep DRY.
However, I am having TypeError: Cannot read property 'subscribe' of undefined
, and I don't know why it's happening.
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);
}
}
And this is app component that uses this directive
解决方案You need to initialize the output:
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);
}
}
You could also use the @HostListener
decorator:
@Directive({
selector: '[my-directive]'
})
export class MyDirective {
@HostListener('myEvent')
myEvent:EventEmitter<any> = new EventEmitter(); // <-----
constructor() {
console.log('>>>>>>>>> this.myEvent', this.myEvent);
}
}
这篇关于angular2 指令“无法使用输出元数据读取未定义的属性“订阅"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论