好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

angular5中的自定义指令(属性指令)

属性型指令用于改变一个 DOM 元素的外观或行为。

在 Angular 中有三种类型的指令:

组件 — 拥有模板的指令

结构型指令 — 通过添加和移除 DOM 元素改变 DOM 布局的指令

属性型指令 — 改变元素、组件或其它指令的外观和行为的指令。

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

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

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

@Directive({ selector:   '  [appHighlight]  '   })

export   class   HighlightDirective {

constructor() { } 
} 

 

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

你可以在指令的构造函数中注入  ElementRef ,来引用宿主 DOM 元素,

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

 

使用方法:

<p appHighlight>Highlight me!</p>

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


先把  HostListener  加进导入列表中。

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

然后使用  HostListener  装饰器添加两个事件处理器,它们会在鼠标进入或离开时进行响应。

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

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

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

 

src/app/highlight.directive.ts  文件如下:

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;
  }

 Ps:这个demo的小例子是按照官网来的,是一个很经典的教程,为了偷懒,所以直接复制过来了。希望老司机们不要喷。谢谢

但是这样写的话太死板了,不够灵活。。。比如说:我想鼠标经过不同的div元素的时候,实现不同的背景颜色,那这个时候就要用到数据绑定向指令传值了(@Input);

直接把最终的代码贴上来吧(运行下面的代码可以试试)

  src/app/highlight.directive.ts  文件如下:

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

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

  constructor(private el: ElementRef) {
  }

  @Input() appHighlight: string;

  @HostListener('mouseenter') onMouseEnter() {
    this.highlight(this.appHighlight || 'red');
  }

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

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

使用的方法是:

  <div> 
   <input   type = "radio"   name = "colors"  ( click ) = "color='lightgreen'" > Green
   <input   type = "radio"   name = "colors"  ( click ) = "color='yellow'" > Yellow
   <input   type = "radio"   name = "colors"  ( click ) = "color='cyan'" > Cyan
 </div> 
 <p  [ appHighlight ] = "color" > Highlight me! </p>                                                              

查看更多关于angular5中的自定义指令(属性指令)的详细内容...

  阅读:36次