天天看點

SAP Spartacus 自定義指令的實作以及通過@HostBinding實作屬性綁定2021-1-12 星期二

SAP Spartacus 自定義指令的實作以及通過@HostBinding實作屬性綁定2021-1-12 星期二
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屬性綁定的目的。

SAP Spartacus 自定義指令的實作以及通過@HostBinding實作屬性綁定2021-1-12 星期二

directive施加的host元素一旦發生keydown事件,會自動觸發directive實作的onKeydown函數,每觸發一次,修改color和borderColor屬性的值,達到host元素變色的效果:

SAP Spartacus 自定義指令的實作以及通過@HostBinding實作屬性綁定2021-1-12 星期二

2021-1-12 星期二

經過測試,使用Directive不需要中括号:

SAP Spartacus 自定義指令的實作以及通過@HostBinding實作屬性綁定2021-1-12 星期二