Angular6在自定义指令中使用@HostBingDing() 和@HostListener()

emmm,,,最近在为项目的第二阶段铺路,偶然看到directive,想想看因为项目已经高度集成了第三方组件,所以对于自定义指令方面的经验自己实在知之甚少,后面经过阅读相关资料,总结一篇关于在自定义指令中使用@HostBingDing() 和@HostListenner()。

在使用这两个属性之前,必须明白一件事,就是在angular中有三种directive:

如图所示,component与其他两个directive的一个很明显的区别就是component有template

宿主(host)

下面提到的一个宿主术语,在angular中宿主可以是component也可以是element

@HostBinding() 装饰器

设置宿主的属性,比如样式: height,width,color,margin, border等等

用法: @HostBingding()接受一个参数,这个参数用于指定宿主的属性的名字

@HostBinding('class.active')

@HostBinding('disabled')

@HostBinding('attr.role')

@HostListener() 装饰器

处理宿主的事件,比如mouseover, mosuout, keydown等等

用法:@HostListener() 接受一个参数,该参数用于指定宿主的事件的名字

举个例子

使用命令行生成rainbow自定指令

ng g directive rainbow

这里定义个自定义指令 raibow,directive.ts

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

@Directive({
  selector: '[appRainbow]'
})
export class RainbowDirective {
    possibleColors = [
        'darksalmon', 'hotpink', 'lightskyblue', 'goldenrod', 'peachpuff',
        'mediumspringgreen', 'cornflowerblue', 'blanchedalmond', 'lightslategrey'
    ];

    @HostBinding('style.color') color: string;
    // @HostBinding('style.border-color') borderColor: string;
    @HostBinding('style.border-bottom-color') borderBottomColor: string;

    @HostListener('keydown') newColor() {
        const colorPick = Math.floor(Math.random() * this.possibleColors.length);

        this.color = this.borderBottomColor = this.possibleColors[colorPick];
    }
}

在任意宿主中使用该指令

<input type="text" appRainbow>

最终效果:

不知道为虾米动态图片上传不了,大概就是每次输入键盘input的边框和文字的颜色会随机动态改变

 

posted @ 2018-06-14 15:09  承蒙时光  阅读(2602)  评论(0编辑  收藏  举报