美文网首页
Angular4 自定义指令

Angular4 自定义指令

作者: 叮铃桄榔_f7cb | 来源:发表于2018-07-18 15:18 被阅读0次

    1. 创建指令文件

    ng generate directive highlight

    2.在highlight.directive.ts 中加入自定义样式(使用 HostListener 装饰器添加两个事件处理器,它们会在鼠标进入或离开时进行响应)

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

    @Directive({

      selector: '[appHighlight]'

    })

    export class HighlightDirective {

    @Input('appHighlight')  highlightColor: string;  //highlightColor是appHighlight指令的别名

      constructor(private el: ElementRef) {

      //  el.nativeElement.style.backgroundColor = 'yellow';

      }

      private highlight(color: string) {

        this.el.nativeElement.style.backgroundColor = color;

      }

      @HostListener('mouseenter') onMouseEnter() {

        this.highlight(this.highlightColor);

      }

      @HostListener('mouseleave') onMouseLeave() {

        this.highlight(null);

      }

    }

    3.在app.module.ts 中引入指令文件

    import { HighlightDirective } from './highlight.directive';

    declarations:[ HighlightDirective ]

    4.在app.component.html 中应用指令

    <p appHighlight>Highlight me!</p>  // 直接应用

    5.运行本应用并确认:当把鼠标移到 p 上的时候,背景色就出现了,而移开的时候,它消失了

    使用 @Input 数据绑定向指令传递值

    6.在app.component.ts中定义属性

    color = 'yellow';

    7. 在app.component.html 中应用指令

     <p [appHighlight]="color" > Highlight me!</p>  

    相关文章

      网友评论

          本文标题:Angular4 自定义指令

          本文链接:https://www.haomeiwen.com/subject/bsuopftx.html