首页 > 其他 > 详细

Angular:自定义属性指令

时间:2020-08-01 21:27:30      阅读:85      评论:0      收藏:0      [点我收藏+]

①在命令行窗口下用 CLI 命令ng g directive创建指令类文件

技术分享图片

②将directives/light.directive.ts文件改造一番

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

/* 可以在指令的构造函数中使用 ElementRef 来注入宿主 DOM 元素的引用,也就是你放置 appLight 的那个元素。
ElementRef 通过其 nativeElement 属性给你了直接访问宿主 DOM 元素的能力。 */
/* @HostListener 装饰器让你订阅某个属性型指令所在的宿主 DOM 元素的事件,在这个例子中就是 <p> */
/* 注意看 @Input 装饰器。它往类上添加了一些元数据,从而让该指令的 highlightColor 能用于绑定 */

@Directive({
  selector: ‘[appLight]‘
})
export class LightDirective {
  @Input(‘appLight‘) highlightColor: string;  //这里相当于是给传入的参数appLight取了一个别名

  constructor(private el: ElementRef) { }

  @HostListener(‘mouseenter‘) onMouseEnter(): void {
    this.highlight(this.highlightColor || ‘red‘);
  }

  @HostListener(‘mouseleave‘) onMouseLeave(): void {
    this.highlight(null);
  }

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

}

③在其他组件中使用

<!-- 注意此处需传"blue",否则就是变量名了 -->
<p [appLight]=‘"blue"‘>鼠标悬浮</p>

 

Angular:自定义属性指令

原文:https://www.cnblogs.com/xinhej/p/13415041.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!