一、 id选择器
1、 文件 app.hightlight.directive.component.ts :
import { Directive, ElementRef, Input } from '@angular/core'; @Directive({ selector: '#appHightLight', }) export class AppHightLightDirective { constructor(private el: ElementRef) { el.nativeElement.style.background = 'red'; } }
效果:
二: 类选择器:
import { Directive, ElementRef, Input } from '@angular/core'; @Directive({ selector: '.appHightLight', }) export class AppHightLightDirective { constructor(private el: ElementRef) { el.nativeElement.style.background = 'red'; } }
html 文件中:
<div class="appHightLight"> 自定义样式 </div>
三: 属性选择器
import { Directive, ElementRef, Input } from '@angular/core'; @Directive({ selector: '[appHightLight]', }) export class AppHightLightDirective { constructor(private el: ElementRef) { el.nativeElement.style.background = 'red'; } }
html文件:
<div appHightLight> 自定义样式 </div>
三:根据传入的值改变样式:
文件 app.hightlight.directive.component.ts :
import { Directive, ElementRef, HostListener, Input, OnInit } from '@angular/core'; @Directive({ selector: '[hightlight]', }) export class AppHightLightDirective { @Input() hightlight: any; constructor(private el: ElementRef) { alert(this.hightlight) console.log("constructor:" + this.hightlight) if (this.hightlight == null) { el.nativeElement.style.background = 'red'; } else { el.nativeElement.style.background = "pink"; } } ngOnInit(): void { //Called after the constructor, initializing input properties, and the first call to ngOnChanges. //Add 'implements OnInit' to the class. alert("init:" + this.hightlight) console.log("init:" + this.hightlight) if (this.hightlight == null) { this.el.nativeElement.style.background = 'green'; } else { this.el.nativeElement.style.background = this.hightlight; } } }
html传入的值:
<div [hightlight]='"pink"'> 自定义样式 </div>