其他分享
首页 > 其他分享> > angular 自定义指令

angular 自定义指令

作者:互联网

一、 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