600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > SAP Spartacus 自定义指令的实现以及通过@HostBinding实现属性绑定

SAP Spartacus 自定义指令的实现以及通过@HostBinding实现属性绑定

时间:2018-07-22 06:42:01

相关推荐

SAP Spartacus 自定义指令的实现以及通过@HostBinding实现属性绑定

使用命令行ng g d color:

实现源代码:

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.borderColor') borderColor: string;@HostListener('keydown') onKeydown(){const colorPick = Math.floor(Math.random() * this.possibleColors.length);console.log('Jerry colorPick: ' + colorPick);this.color = this.borderColor = this.possibleColors[colorPick];}}

定义一个input field:

<input appRainbow/>

在directive实现内部,通过@HostBinding达到directive施加的host元素的css样式和directive属性绑定的目的。

directive施加的host元素一旦发生keydown事件,会自动触发directive实现的onKeydown函数,每触发一次,修改color和borderColor属性的值,达到host元素变色的效果:

-1-12 星期二

经过测试,使用Directive不需要中括号:

要获取更多Jerry的原创文章,请关注公众号"汪子熙":

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。