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

时间:2022-07-26
本文章向大家介绍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元素变色的效果: