天天看点

Angular 自定义指令

创建指令:ng g directive directive/lcstyle

导入ElementRef且注入进来

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

@Directive({
  selector: '[appLcstyle]'
})
export class LcstyleDirective {
  @Input() appLcstyle: any;
  constructor(public ref: ElementRef) {//把ElementRef注入进来
    console.log("constructor")
   }
  ngOnChanges(){
    console.log(this.appLcstyle);
    console.log("在数据发生变化之时就会调用此函数");
    console.log(this.ref);
    this.ref.nativeElement.className = this.appLcstyle;
  }
}      
<h1 [appLcstyle]="'abc'"></h1>      

继续阅读