ng2自定义指令 directive

前端之家收集整理的这篇文章主要介绍了ng2自定义指令 directive前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1、自定义指令

  1. /*
  2. * Directive: 指令模块
  3. * ElementRef: 获取节点
  4. * Input: 获取输入内容
  5. * Renderer: 渲染新节点
  6. * HostListener: 这是监听事件的,绑定时间
  7. *
  8. * 注意:
  9. * 1. 指令的名称要使用中括号括起来
  10. * 2. html中使用的时候,不需要中括号
  11. * 3. 构造模板中传递参数的时候,如果是字符串,那么要单引号: [myHighlight]="'blue'"
  12. */
  13. import {Directive,ElementRef,HostListener,Input,Renderer} from '@angular/core';
  14. @Directive({
  15. selector: '[myHighlight]'
  16. })
  17. export class OneDirective {
  18. constructor(private el:ElementRef,private renderer:Renderer) {
  19.  
  20. }
  21.  
  22. // 给myHighlight指令定义一个输入变量(外部调取这个指令传递的参数)
  23. @Input("myHighlight") chColor: string;
  24.  
  25. @HostListener("click") onClick() {
  26. // 调用函数,传递指令外部获取的颜色
  27. this.changeColor(this.chColor);
  28. }
  29. // 自定义函数
  30. public changeColor(color: string) {
  31. this.renderer.setElementStyle(this.el.nativeElement,"background-color",color);
  32. }
  33. }

2、app.module.ts主模块中引入指令

  1. import {HighLight} from "../directive/high-light.directive.ts"
  2. @ngModule({
  3. declarations: [
  4. HighLight
  5. ]
  6. })

3、模板中使用指令

  1. <p myHighlight="yellow">
  2. 自定义指令
  3. </p>

猜你在找的Angularjs相关文章