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

    科技2024-04-09  88

    使用命令行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元素变色的效果:

    2021-1-12 星期二

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

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

    汪子熙 认证博客专家 前端框架 Node.js SAP JerryWang,2007年从电子科技大学计算机专业硕士毕业后加入SAP成都研究院工作至今。Jerry是SAP社区导师,SAP中国技术大使。2020年5月下旬,Jerry做了脑部肿瘤的开颅切除手术,对编程和人生又有了新的感悟。
    Processed: 0.010, SQL: 8