angular自定义指令

指令分类 

  angular的指令分为三类:属性指令、结构指令、动态指令。

属性指令

       之前在使用angular的时候,大家都曾使用过[ngClass]=""这个吧,这个就是属性指令,是angular内置的属性指令。属性指令顾名思义就是定义后,用于HTML元素内作为属性使用的。

定义

import { Directive, ElementRef } from '@angular/core'; 
@Directive({    //与组件定义相似,同样是装饰器
  selector: '[appHighlight]'
  })
    export class HighlightDirective {
      constructor(el: ElementRef) {
        el.nativeElement.style.backgroundColor ='yellow'
      }       
 }

好了,一个简单的指令定义好了。

使用如下:

<p appHighlight>Highlight me!</p>

现在p标签背景色变为黄色了。

现在将其改为事件可控制的方式,鼠标移动上去变色,移出恢复原样,如下:

import { Directive, ElementRef, HostListener } from '@angular/core'; 
@Directive({    //与组件定义相似,同样是装饰器
  selector: '[appHighlight]'
  })
export class HighlightDirective {
      constructor(el: ElementRef) {}        //不必再在构造器为期初始化背景色,而只是定义映射,背景色变色通过事件监听实现

    
   @HostListener('mouseenter') onMouseEnter() {    //鼠标放上去触发
     this.highlight('yellow');
   }

   @HostListener('mouseleave') onMouseLeave() {    //鼠标离开触发
     this.highlight(null);
   }
   private highlight(color: string) {
     this.el.nativeElement.style.backgroundColor = color;
   }

}

这样看上去可以变化了,但是只能变化为黄色和无色,那么想要灵活变化颜色怎么办呢?通过之前的父子组件传值即可解决,如下:

import { Directive, ElementRef, HostListener,Input } from '@angular/core'; 
@Directive({    //与组件定义相似,同样是装饰器
  selector: '[appHighlight]'
  })
export class HighlightDirective {
     @Input() highlightColor:string;
      constructor(el: ElementRef) {}        //不必再在构造器为期初始化背景色,而只是定义映射,背景色变色通过事件监听实现

    
   @HostListener('mouseenter') onMouseEnter() {    //鼠标放上去触发
     this.highlight('yellow');
   }

   @HostListener('mouseleave') onMouseLeave() {    //鼠标离开触发
     this.highlight(null);
   }
   private highlight(color: string) {
     this.el.nativeElement.style.backgroundColor = color;
   }

}

 

原文地址:https://www.cnblogs.com/hzozj/p/11011237.html