Event handling and change detection in Angular 2

I’m really loving the new template syntax in Angular 2. Especially for binding events:

<button (click)="doSomething()">Click Me!</button>

You don’t have to use a directive. You only need to know the name of the event and the parenthesis are a good visual indicator of the direction the message is flowing.

One of the great things about Angular 2 is that there is no longer a digest cycle and no $scope. As such, you no longer have to depend on all the extra directives and angular APIs to do things and your code can be much more natural. In this example, I show how you can listen to keyboard events on the global window object with two different mechanisms: using Angular’s (event)=handler syntax and the traditional addEventListener() API.

Take a look at the demo app: http://matthewcv.github.io/blogs/angular2events.html

You use the keyboard to toggle the visibility of the boxes. For the green box, I am using the angular template syntax. The difference here is that I am applying the event handler in the host property of the Component annotation:

 AppComponent.annotations = [
   new ng.core.Component({
     selector:'my-app',
     directives:[],
     template:getTpl('my-app'),
     host:{
       '(window:keydown)':'ngKeyDown($event)'
     }
   })
 ]

It doesn’t seem to work when I apply that in the html on the <my-app> element. The window: part tells angular to bind the event to the window object rather than the <my-app> element.

For the red box, i am using the addEventListener API in the constructor of my component. The handlers simple toggle a boolean value which is bound to an ngIf directive on each of the colored boxes. Both mechanisms work exactly the same as you would expect. This wouldn’t work at all in angular 1. You’d have to make an explicit call to $scope.$apply().

An important note

Using addEventListener works and it’s great that it works but it is strongly recommended that you do not use this in your components and directives. There are a couple reasons for it:

  1. It couples your code directly to the browser API which means that your component won’t work anywhere else – like server side rendering or web-workers.
  2. When you use the (event) syntax, you get a bunch of extra help from angular for free. Angular will automatically call the listener in the scope of your controller so ‘this’ in your function will work as you expect. Angular will automatically remove the event listener when the component is destroyed which will prevent memory leaks. This is a thing you had to do manually in Angular 1 custom directives.

One thought on “Event handling and change detection in Angular 2

Leave a Reply

Your email address will not be published. Required fields are marked *