0%

Angular2 自定义指令

Angular的指令分为三种:

  1. 属性指令

    属性指令指的是以属性形式使用的指令,如NgClass,NgStyle,FormsModule里的NgModel,NgModelGroup等。

  2. 结构指令

    结构指令用于修改DOM结构,如NgIf,当条件为true时,该元素会被添加到DOM中。

  3. 组件

    这个不必说了,我们用得最多的便是组件。与其他指令不同,它描述的是一个视图,是用户可以直接看到的东西。

自定义属性指令

添加一个color属性,支持传入颜色名参数,设置标签内文本的颜色。

  1. 创建directive:

    ng g directive color

  2. 编写代码

    color.directive.ts :

    import {Directive, ElementRef, Input, AfterViewInit} from '@angular/core';
    
    @Directive({
      selector: '[color]'
    })
    export class ColorDirective implements AfterViewInit {
      _defaultColor='black';
      ngAfterViewInit(): void {
    
      }
      //参数 setter
      @Input('color') set color(colorName:string) {
        this.setFontColor(colorName);
      };
      constructor(private el:ElementRef) {
        this.setFontColor(this._defaultColor);
      }
    
      setFontColor(color:string) {
          this.el.nativeElement.style.color=color;
      }
    }
    
  3. 应用属性

    <h1 color="green">
      { {title}}
    </h1>
    

    此时,该h1标签内容的颜色为绿色

自定义结构指令

结构指令需要在构造方法注入TemplateRef和ViewContainerRef这两个服务,TemplateRef用于访问组件模板,ViewContainerRef用于往DOM插入或移除模板,此处不作演示。