Web 前端开发

Angular2--属性型指令

2016-12-18  本文已影响1468人  紫诺_qiu

属性型指令

创建属性型指令

import { Directive, ElementRef, Input, Renderer } from '@angular/core';
@Directive({ selector: '[myHighlight]' })
export class HighlightDirective {
    constructor(el: ElementRef, renderer: Renderer) {
       renderer.setElementStyle(el.nativeElement, 'backgroundColor', 'yellow');
    }
}
  1. Directive 提供@Directive装饰器功能
  2. ElementRef 注入到指令构造函数中,使代码可以访问DOM元素。
  3. Input 就是将数据从绑定表达式传到指令中。
  4. Renderer 让代码可以改变DOM元素的样式。
  5. HighlightDirective是指令的控制器类,包括了指令的工作逻辑

PS:属性指令的@Directive装饰器需要一个CSS选择器,以便从模板中识别出关联到这个指令的HTML,CSS 中的attribute选择器就是属性名称加方括号,如例子中的[myHighlight].

属性型指令的应用

<h1>My First Attribute Directive</h1>
<p myHighlight>Highlight me!</p>

响应用户引发事件

import { Directive, ElementRef, HostListener, Input, Renderer } from '@angular/core';
@Directive({
  selector: '[myHighlight]'
})
export class HighlightDirective {
  constructor(private el: ElementRef, private renderer: Renderer) { }
  @HostListener('mouseenter') onMouseEnter() {
    this.highlight('yellow');
  }
  @HostListener('mouseleave') onMouseLeave() {
    this.highlight(null);
  }
  private highlight(color: string) {
    this.renderer.setElementStyle(this.el.nativeElement, 'backgroundColor', color);
  }
}

使用数据绑定向指令传递值

export class HighlightDirective {
  private _defaultColor = 'red';

  constructor(private el: ElementRef, private renderer: Renderer) { }
/** 增加一个可绑定的输入型指令*/
  @Input('myHighlight') highlightColor: string; 

  @HostListener('mouseenter') onMouseEnter() {
    this.highlight(this.highlightColor || this._defaultColor);
  }
  @HostListener('mouseleave') onMouseLeave() {
    this.highlight(null);
  }
  private highlight(color: string) {
    this.renderer.setElementStyle(this.el.nativeElement, 'backgroundColor', color);
  }
}
<p [myHighlight]="color">Highlight me!</p>

绑定第二个属性

@Input() set defaultColor(colorName: string){
this._defaultColor = colorName || this._defaultColor;
}
<p [myHighlight]="color" [defaultColor]="'violet'">
  Highlight me too!
</p>
上一篇下一篇

猜你喜欢

热点阅读