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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With