1. 程式人生 > 其它 >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>