【问题标题】:Angular directive listen to element style changeAngular 指令监听元素样式变化
【发布时间】:2018-04-24 01:38:14
【问题描述】:

您好,我有这个指令可以为元素添加背景颜色:

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 中使用它,并且该组件总是更改样式然后覆盖我的指令结果,那么有没有办法在覆盖后应用我的指令?

【问题讨论】:

  • 什么时候改颜色?
  • 看看 observable 和 observer 对象,您应该能够在组件渲染后(或任何时候)应用触发器来改变颜色
  • @Aravind:我不希望这个动态改变颜色,我只想用来建立颜色,但如果我在我的元素中使用style="backgrond-color..." ngx-slick 覆盖这个规则,所以我认为使用指令是最好的解决方案
  • @FabioGuerrazzi,你能给我举个例子吗?
  • 是的,我正在寻找它,stackoverflow.com/questions/41274603/…

标签: angular angular2-directives angular-directive


【解决方案1】:

使用数据绑定,这样 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 导入的,如果你想绑定到单个属性或对象,它需要一个字符串。

【讨论】:

  • 感谢您的回答,我还找到了另一个解决方案,将 ngAfterViewInit 更改为 ngDoCheck 并为我工作,您的解决方案是否是我的最佳解决方案?这是我开始学习的第一个指令。
  • @efirvida 我对哪种方法更好没有意见。我没有看到任何明显的优势。
猜你喜欢
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
  • 2019-10-07
  • 2014-02-14
  • 2019-03-27
  • 2012-11-02
  • 1970-01-01
  • 2022-08-02
相关资源
最近更新 更多