微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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>

  

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐