Angular @HostBinding()和@HostListener()用法

网友投稿 420 2023-02-14


Angular @HostBinding()和@HostListener()用法

@HostBinding()和@HostListener()在自定义指令时非常有用。@HostBinding()可以为指令的宿主元素添加类、样式、属性等,而@HostListener()可以监听宿主元素上的事件。

@HostBindingNJkDFsTiF()和@HostListener()不仅仅用在自定义指令,只是在自定义指令中用的较多

本文基于Angular2+

下面我们通过实现一个在输入时实时改变字体和边框颜色的指令,学习@HostBinding()和@HostListener()的用法。

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.colorhttp://') color: string;

@HostBinding('style.borderColor') borderColor: string;③

@HostListener('keydown') onKeydown(){④

const colorPick = Math.floor(Math.random() * this.possibleColors.length);

this.color = this.borderColor = this.possibleColors[colorPick];

}

}

说一下上面代码的主要部分:

①:为我们的指令取名为appRainbow

 ②:定义我们需要展示的所有可能的颜色

③:定义并用@HostBinding()装饰color和borderColor,用于设置样式

④:用@HostListener()监听宿主元素的keydown事件,为color和borderColor随机分配颜色

OK,现在就来使用我们的指令:

效果就像这样:

NOTE:别忘了把指令引入你的模块


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:api接口文档管理器(接口文档软件)
下一篇:Spring Security 图片验证码功能的实例代码
相关文章

 发表评论

暂时没有评论,来抢沙发吧~