该指令用于演示如何利用 HostBinding 装饰器,设置元素的 innerText 属性。

Angular6 手动创建指令_Angular6 手动创建指令

greet.directive.ts

import { Directive, HostBinding} from '@angular/core';

@Directive({
    selector: '[greet]'
})
export class GreetDirective {
  @HostBinding() innerText = 'Hello, Everyone!';
}

app.component.html

<h2>hello angular</h2>
<h2 greet>hello angular</h2>

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { GreetDirective } from './directive/greet.directive';

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent, GreetDirective ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

效果图:

Angular6 手动创建指令_Angular6 手动创建指令_02