read

In a previous article, we looked at how components in Angular 2 can communicate with each using properties. You can pass in values or bind expressions, but this doesn't cover all use cases.

What if you wanted to run a function on a parent component? Or pass a value into that same function on the parent? This is where Event Emitters come in.

Let's look at an example. We'll bubble up a value between classes. Event Emitters are complicated at first, so perhaps it's better to start with an example, then go into details.

Example



Notice that clicking on the button causes both the parent and child to update. The event is bubbling up, but how does that happen?

Event Emitters

Setting up an Event Emitter requires quite a lot of setup.

  • Import the EventEmitter dependency

import {EventEmitter} from 'angular2/angular2';

  • Add it to the list of Component Events
    @Component({
      selector: 'some-component',
      events: ['someEmitter']
    })

Note that events should be camelCased.

  • Instantiate the event emitter with the same name as your Component event
    class SomeComponent {
      constructor() {
        this.someEmitter = new EventEmitter();
      }
    }

If you're using TypeScript, an event emitter can be declared without a constructor.

    class SomeComponent {
      someEmitter: EventEmitter = new EventEmitter();
      constructor() {}
    }
  • Setup an (event) to call your event emitter. Here we'll use (click) which cals the method 'onClick'.

<button (click)="onClick()">Click me!</button>

  • Call the event emitter with .next() and pass in a value.
    class SomeComponent {
      onClick() {
          this.someEmitter.next({
            value: ++this.counter
          });
      }
    }

The iterator, .next() could take a text value, object, or whatever you're looking to communicate.

Note: i++ adds one to i after the expression runs, ++i runs it before. Change the values in the example to see the difference

  • Finally, catch the event on the parent component by adding the event to the component element.

<some-component (some-emitter)="onUpdate($event)></some-component>

Note that the emitter must be snake-cased.

Also note that $event contains the data being passed in from the child component.

  • This will run the attached function on the parent component.
    class ParentComponent {
      onUpdate(event) {
         this.counter = event.value;
      }
    }

Conclusion

Event Emitters are a powerful way to communicate between components in Angular2. They allow you to pass events between components, and run functions on parent components.

On the bright side, the event communication pathway is made expressly clear. This may look complicated, but later we'll look at easier way to handle events using hostListeners with Directives.



Angular 2 Series
Event Emitters | Properties | Pipes | Meteor

Blog Logo

Shawn McKay

Published

Image

ShMcK

JavaScript Web Dev

Back Home