Angular指令监听元素样式的变化

时间:2017-11-10 18:48:16

标签: angular angular2-directives angular-directive

您好我有这个指令将背景颜色添加到元素:

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中使用它,这个组件总是改变样式然后覆盖我的指令结果,所以有没有办法在覆盖后应用我的指令?

1 个答案:

答案 0 :(得分:2)

使用数据绑定,因此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导入,如果要绑定到单个属性或对象,则需要一个字符串。

相关问题