Event Emitters (Outputs)

Just as an anchor can emit a click event, and a form can emit a submit event, our custom components can emit events that we make up too.

For example, say we have a likes button. We might have it output a 'like' event and an 'unlike' event. If we have a rating star component, we might have it emit a 'rate' event. We might extend that event object to include the number of stars.

We need to do 3 things to make our component emit an event:

Configure our component to emit the event.

Create the event emitter in our component.

Tell the event emitter to emit the event.

Let's do this now. We are going to create a like button. We click it and it emits a 'like' event.

1. Configure the component

First we need to add the 'liked' to our component decorator:

.Component({

selector: "like",

outputs: ["liked"],

template:

`

<a (click)="handleClick()">

Like?

</a>

`

})

This tells Angular that this component will emit a liked event. Notice also that the template is calling a function called handleClick() when we click it.

2. Create the EventEmitter

Next we need to create an attribute of our component object to manage the event. We do this in our class decorator:

.Class({

constructor: function() {

this.liked = new ng.core.EventEmitter();

}

})

This will be an instance of ng.core.EventEmitter.

Emit the event

Finally we need to tell our class to emit the event. Let's extend our Class to handle a click event:

.Class({

constructor: function() {

this.liked = new ng.core.EventEmitter();

this.handleClick = () => {

console.log('clicked');

this.liked.emit();

}

}

})

Putting it together

Here's the whole component:

var LikeButtonComponent = ng.core

.Component({

selector: "like",

outputs: ["liked"],

template:

`

<a (click)="handleClick()">

Like?

</a>

`

})

.Class({

constructor: function() {

this.liked = new ng.core.EventEmitter();

this.handleClick = function() {

console.log('clicked');

this.liked.emit();

}

}

});

Make use of the component

We can now make use of this component in a parent component, like so:

var AppComponent = ng.core

.Component({

selector: "app",

template:

`

<like (liked)="handleLike()">Hello</like>

{{message}}

`

})

.Class({

constructor: function() {

this.handleLike = function() {

this.message = "Thanks for liking us"

}

}

});

Notice the like component is now able to emit a liked event, which we can handle.