Dealing with Browser Events
Angular 2 has a new special syntax for dealing with events. In Angular 1 we had many special case directives to handle user interactions, such as ng-click, ng-submit, etc.
In Angular 2, events are no longer handed by special directives. There is a generic syntax. This means that we can handle any type of DOM event, and also custom events that our components might emit.
We handle a click event like this:
<a (click)="handleClick()">
Click Me!
</a>
If you don't like this syntax, we have a more traditional XML syntax available like so:
<a on-click="handleClick()">
Click Me!
</a>
We then need to define a our handleClick function inside the class decorator, like so:
.Class({
constructor: function() {
this.handleClick = function() {
console.log('clicked');
}
}
})
Put it all together:
var AppComponent = ng.core
.Component({
selector: "app",
template:
`
<a (click)="handleClick()">
Click Me!
</a>
`
})
.Class({
constructor: function() {
this.handleClick = function() {
console.log('clicked');
}
}
})
Dealing with events in the expression
We don't need to shell out to a handler to deal with events, although it's often a good idea. We can write an expression to deal with them right in the template, like so:
var AppComponent = ng.core
.Component({
selector: "app",
template:
`
<a (click)="name = 'Dave'">
My Name is Dave
</a>
{{name}}
`
})
.Class({
constructor: function() {}
})
Exercise - A Click Counter
Make a little click counter. Each time you click a link, the counter should increment.
For bonus points, make a down button as well, so you can change a value with up and down clicks.
*Note that i++ or i+=1 is not currently supported in Angular expressions. You will need to use the longhand i = i + 1;
Getting the Event
We can get a reference to the event by passing $event from the template. This is a real DOM event, complete with all the information you would expect.
<a (click)="handleClick($event)">
Hello World!
</a>
We then handle this in our handler:
this.handleClick = function(event) {
console.log(event);
}
Exercise - Mouse Coordinates
We are going to access the mouse coordinates in a div. Use the following scaffold:
var AppComponent = ng.core
.Component({
selector: "app",
template:
`
<div style="width:400px; height:400px; border:1px solid black"></div>
`
})
.Class({
constructor: function() {}
})
When the user clicks on the div, grab the mouse coordinates from the event and output them on the page.
For bonus points, make this happen when on mousemove