Search code examples
event-handlingangularderived-classbase-classeventemitter

Angular 2 Base Class Output EventEmitter doesn't get raised or handled


Very simple base class Closer

import {EventEmitter, Output} from 'angular2/core';

export class Closer {
  @Output() closed: EventEmitter<any> = new EventEmitter();

  constructor() {}

  close() {
    this.closed.emit({});
  }
}

If I extends Closer another class and then mark it up with

<derived-class (closed)="closeHandler()"></derived-class>

closeHandler() will never get called. I can see Closer.close() getting called but the emit doesn't get propagated by the derived class or handled by the class whose template contains the derived class and event binding.

If I simply move the @Output to the derived class it works. But it would seem that Angular2 should be putting that on derived classes. The ability to fully define a set of behavior and inherit it would be nice.


Solution

  • I had the same problem this morning and just figured out how to do it. All you have to do is add outputs: ['closed'] to the components section of the derived class that is extending Closer and you have to remove @Output() from the closed declaration inside the Closer class

    Here is a quick demo based on your example:

    Derived Class:

    @Component({
      selector: 'derived-class',
      outputs: ['closed']
    })
    export class DerivedClass extends Closer {}
    

    Closer Class:

    import {EventEmitter} from 'angular2/core';
    
    export class Closer {
      closed: EventEmitter<any> = new EventEmitter();
    
      constructor() {}
    
      close() {
        this.closed.emit({});
      }
    }