zoukankan      html  css  js  c++  java
  • 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的边框和文字的颜色会随机动态改变

  • 相关阅读:
    word文档中画垂直或水平的线条
    word文档中把几个图形组合在一起
    设计模式
    确认删除的提示的JQuery
    Incorrect column count: expected 1, actual 4 问题
    Spring MVC 中的 controller层的方法的返回值类型
    SpringBoot 项目用户登录
    使用模板异常的解决
    Redis配置到本地以及可视化工具的安装运用
    第034讲:丰富的else语句及简洁的with语句 | 课后测试题及答案
  • 原文地址:https://www.cnblogs.com/timetimetime/p/9183091.html
Copyright © 2011-2022 走看看