Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 848
jkyoutsey Avatar asked Apr 05 '16 18:04

jkyoutsey


People also ask

What does .emit do in Angular?

EventEmitterlink. Use in components with the @Output directive to emit custom events synchronously or asynchronously, and register handlers for those events by subscribing to an instance.

How do you pass two parameters in EventEmitter?

For passing the parameters, we will wrap all the parameters inside the curly brackets (this will combine them as a single object) and pass it to the emit method. To receive the parameters in the parent component, we will make a similar type of object and update its value with that of the received object.

How do I declare EventEmitter?

Simply use it to emit events from your component. Take a look a the following example. @Component({ selector : 'child', template : ` <button (click)="sendNotification()">Notify my parent! </button> ` }) class Child { @Output() notifyParent: EventEmitter<any> = new EventEmitter(); sendNotification() { this.


1 Answers

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({});
  }
}
like image 189
Marin Petkov Avatar answered Oct 28 '22 16:10

Marin Petkov