1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > angular5中的自定义指令(属性指令)

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

时间:2019-02-13 10:33:30

相关推荐

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>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。