Angular Event Binding Syntax


Angular 2’s binding syntax is a little strange at first but after a while it does make sense when you get familar with all the different types of bindings.

The basic syntax for event binding is …

eventName = "functionToCall()";

… where eventName is a native DOM event and functionToCall is a function in the component’s class. You can pass the native event argument in using $event.

Below is an example of a search input component …

import { Component } from "angular2/core";
@Component({
selector: "my-search",
template: `
<input
#criteria
type="text"
placeholder="Enter criteria"
(keypress)="preventNumbers($event)"
/>
<button (click)="search(criteria.value)">Search</button>
`
})
export class MySearchComponent {
preventNumbers(e) {
console.log(e.keyCode);
if (e.keyCode >= 48 && e.keyCode <= 57) {
// we have a number
return false;
}
}
search(criteria) {
console.log("search for " + criteria);
}
}

Some key points …

  • On line 6 we bind to the keypress event on the textbox calling the preventNumbers() function. We pass in the native event argument using $event
  • On line 6 we also use a local variable, #criteria, so that we can reference the textbox in the button’s binding on line 7
  • On line 7 we bind to the click event on the button calling the search() function passing in the value of the search textbox.

Learn React with TypeScript - 3rd Edition

New

A comprehensive guide to building modern React applications with TypeScript. Learn best practices, advanced patterns, and real-world development techniques.

View on Amazon
Learn React with TypeScript - Third Edition