Angular 2 Directives allow you manipulate elements by adding custom behaviors through attributes. This lesson covers how to create a Directive and attach its behavior to an element.
import {Directive, HostBinding} from '@angular/core'; @Directive({ selector: '[myText]' }) export class TextDirective { @HostBinding() innerText; constructor() { this.innerText = "I am text directive!" } }
There are tow things important here:
- selector: '[myText]', this is an attr selector.
- HostBinding: Bind to host element's props.
If we using like this:
<div myText>I am a div</div> <span>I am a span</span> <hr> <span myText>My text will be changed!</span>
This directive will change div and last span's innerText to 'I am text directive!'.