标签:el style 自定义 Directive ElementRef 指令 background angular hightlight
一、 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>
标签:el,style,自定义,Directive,ElementRef,指令,background,angular,hightlight 来源: https://www.cnblogs.com/z360519549/p/16122960.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。