天天看點

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>      

繼續閱讀