Carl Rippon

Building SPAs

Carl Rippon
BlogBooks / CoursesAbout
This site uses cookies. Click here to find out more

Angular Event Binding Syntax

December 30, 2015
angulartypescript

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.

If you to learn more about TypeScript, you may find my free TypeScript course useful:

Learn TypeScript

Learn TypeScript
Take a look

Want more content like this?

Subscribe to receive notifications on new blog posts and courses

Required
© Carl Rippon
Privacy Policy