Referencing elements using template variables
Many developers will begin with Angular 2 and reach for something that resembles the trustworthy ng-model
in Angular 1. NgModel
exists in Angular 2, but there is a new way of referencing elements in the template: local template variables.
Note
The code, links, and a live example of this are available at http://ngcookbook.herokuapp.com/5094/.
Getting ready
Suppose you had the following application and wanted to directly access the input
element:
[app/article.component.ts] import {Component} from '@angular/core'; @Component({ selector: 'article', template: ` <input> <h1>{{title}}</h1> ` }) export class ArticleComponent {}
How to do it...
Angular 2 allows you to have a #
assignment within the template itself, which can consequently be referenced from inside the template. For example, refer to the following code:
[app/article.component.ts] &...