嗨,我有此指令可以将背景色添加到元素中:
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导入的,如果要绑定到单个属性或对象,则需要一个字符串。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句