angular自定义属性指令

在angular中有三种类型的指令:
  1. 组件–拥有模板的指令;
  2. 结构性指令–经过添加和移除DOM元素改变DOM布局的指令;
  3. 属性型指令–改变元素、组件或其余指令的外观和行为的指令;
组件是这三种指令中最经常使用的。结构性指令修改视图的结构,例如ngfor和ngif。属性型指令改变一个元素的外观或行为。

属性型指令至少须要一个带有 @Directive 装饰器的控制器类。该装饰器指定了一个用于标识属性的选择器。 控制器类实现了指令须要的指令行为。html

好比定义一个名为“highlight”的属性型指令:

在cmd的命令窗口里面执行命令:ng generate directive highlightjson

生成的 src/app/highlight.directive.ts 文件以下:app

import { Directive } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor() { }
}
View Code

这里导入的 Directive 符号提供了 Angular 的 @Directive 装饰器。ide

@Directive 装饰器的配置属性中指定了该指令的 CSS 属性型选择器 [appHighlight]函数

这里的方括号([])表示它的属性型选择器。 Angular 会在模板中定位每一个拥有名叫 appHighlight 属性的元素,而且为这些元素加上本指令的逻辑。布局

正因如此,这类指令被称为 属性选择器 。this

在构造函数里加相关逻辑,好比,实现把宿主元素的背景色设置为黄色:spa

import { Directive, ElementRef } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
    constructor(el: ElementRef) {
       el.nativeElement.style.backgroundColor = 'yellow';
    }
}
View Code

 

import 语句还从 Angular 的 core 库中导入了一个 ElementRef 符号。code

你能够在指令的构造函数中使用 ElementRef 来注入宿主 DOM 元素的引用,也就是你放置 appHighlight 的那个元素。htm

ElementRef 经过其 nativeElement 属性给你了直接访问宿主 DOM 元素的能力。

这里的第一个实现把宿主元素的背景色设置为了黄色。

使用属性型指令:
<p appHighlight>Highlight me!</p>

  

总结:Angular 在宿主元素 p 上发现了一个 appHighlight 属性。 而后它建立了一个 HighlightDirective 类的实例,并把所在元素的引用注入到了指令的构造函数中。 在构造函数中,该指令把 p 元素的背景设置为了黄色。

以上只是简单的设置元素的颜色,若是须要鼠标悬浮一个元素时,设置它的颜色,响应用户引起的事件:

先把 HostListener 加进导入列表中。

src/app/highlight.directive.ts (imports):

import { Directive, ElementRef, HostListener } from '@angular/core'; 

而后使用 HostListener 装饰器添加两个事件处理器,它们会在鼠标进入或离开时进行响应。
src/app/highlight.directive.ts (mouse-methods):

@HostListener('mouseenter') onMouseEnter() {
  this.highlight('yellow');
}

@HostListener('mouseleave') onMouseLeave() {
  this.highlight(null);
}

private highlight(color: string) {
  this.el.nativeElement.style.backgroundColor = color;
}
View Code

 

这个辅助方法(highlight)被从构造函数中提取了出来。 修改后的构造函数只负责声明要注入的元素 el: ElementRef。

src/app/highlight.directive.ts (constructor):

constructor(private el: ElementRef) { }

 

下面是修改后的指令代码:

import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor(private el: ElementRef) { }

  @HostListener('mouseenter') onMouseEnter() {
    this.highlight('yellow');
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.highlight(null);
  }

  private highlight(color: string) {
    this.el.nativeElement.style.backgroundColor = color;
  }
}
View Code
相关文章
相关标签/搜索