Angular 指令监听元素样式变化

Angular directive listen to element style change

你好,我有这个指令来为元素添加背景颜色:

import {Directive, ElementRef, AfterViewInit, Input} from '@angular/core';

@Directive({
  selector: '[bg-color]'
})
export class BgColorDirective implements AfterViewInit {
  private el: HTMLElement;
  @Input('bg-color') backgroundColor: string;

  constructor(el: ElementRef) {
    this.el = el.nativeElement;
  }

    ngAfterViewInit() {
      this.el.style.backgroundColor = this.backgroundColor;
    }

}

但在我的例子中,我在另一个组件中使用它 ngx-slick 并且这个组件总是改变样式然后它覆盖我的指令结果,那么有没有办法在覆盖之后应用我的指令?

使用数据绑定,这样 Angular 将有助于保持正确的颜色。将您的指令更改为:

@Directive({
  selector: '[bg-color]'
})
export class BgColorDirective {
  // update color at each input change
  @Input('bg-color') set inputColor(value){this.color = value};

  //data-bind to the host element's style property
  @HostBinding('style.backgroundColor') color = 'white';//default color
}

您仍然可以像以前一样设置背景颜色:

<ngx-slick bg-color="blue"></ngx-slick>
<ngx-slick [bg-color]="someProperty"></ngx-slick>

现在的区别是 @HostBinding 将在每个更改检测周期检查和更新绑定。它是从@angular/core 导入的,如果您想绑定到单个 属性 或对象,它需要一个字符串。