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

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

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

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

宿主(host)

下面提到的一个宿主术语,在angular中宿主能够是component也能够是elementthis

@HostBinding() 装饰器

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

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

@HostBinding('class.active')

@HostBinding('disabled')

@HostBinding('attr.role')

@HostListener() 装饰器

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

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

举个例子

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

ng g directive rainbow

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

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的边框和文字的颜色会随机动态改变

相关文章
相关标签/搜索