zoukankan      html  css  js  c++  java
  • 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;
       }
    
    }

     

  • 相关阅读:
    spring中用到哪些设计模式?
    配置监听器使项目启动时创建消费者
    ActiveMQ依赖JDK版本关系
    ActiveMQ之topic主题模式
    ActiveMQ与Spring整合
    ac自动机模板
    poj 3735 Training little cats矩阵快速幂
    KMP算法模板 求子串和模板串首先匹配的位置
    hdoj 2665 Kth number主席树裸
    vijos P1081野生动物园 主席树求区间第K大
  • 原文地址:https://www.cnblogs.com/hzozj/p/11011237.html
Copyright © 2011-2022 走看看