• 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>
    

      

  • 相关阅读:
    Vue cli 安装慢的原因和解决记录
    spring-boot
    illustrator 2018 cc
    illustrator 2018 cc
    illustrator 2018 cc
    illustrator 2018 cc- 画板技巧
    Tomcat 用户密码配置
    CentOS7上解决tomcat不能被外部浏览访问
    Ubuntu
    SPI、I2C、UART(转)
  • 原文地址:https://www.cnblogs.com/z360519549/p/16122960.html
Copyright © 2020-2023  润新知