Attaching behavior to DOM elements with directives
In the course of creating applications, you will often find it useful to be able to attach component-style behavior to DOM elements, but without the need to have templating. If you were to attempt to construct an Angular 2 component without providing a template in some way, you will meet with a stern error telling you that some form of template is required.
Here lies the difference between Angular 2 components and directives: components have views (which can take the form of a template
, templateUrl
, or @View
decorator), whereas directives do not. They otherwise behave identically and provide you with the same behavior.
Note
The code, links, and a live example of this are available at http://ngcookbook.herokuapp.com/3292/.
Getting ready
Suppose you have the following application:
[app/article.component.ts] import {Component} from '@angular/core'; @Component({ selector: 'article', template: `<h1>{...