Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular2 directive `Cannot read property 'subscribe' of undefined` with outputs metadata

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);
  }
}

enter image description here

And this is app component that uses this directive

enter image description here

like image 322
allenhwkim Avatar asked Jun 11 '16 15:06

allenhwkim


1 Answers

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);
  }
}
like image 132
Thierry Templier Avatar answered Oct 26 '22 22:10

Thierry Templier