我有这个指令,当特定元素滚动时,将样式应用于使用该指令的元素。
@Directive({
selector: `[appFixColumn]`})
export class FixColumnDirective implements AfterViewInit {
constructor(
private changeDetectorRef: ChangeDetectorRef,
private el: ElementRef,
private renderer: Renderer2,
@Inject(DOCUMENT) private document: any
) {}
@HostBinding('style.left') element: any;
ngAfterViewInit() {
const el = this.document.getElementsByClassName('some-element');
if (el[0]) {
el[0].addEventListener('scroll', e => {
this.element = `${el[0].scrollLeft}px`;
});
}
}
}
用法:
<div appFixColumn class="element__column">
<span class="element__name">
Name
</span>
</div>
我可以看到DOM中的元素被更改,但Angular没有检测到更改。
<div _ngcontent-c1="" appfixcolumn="" class="element__column" style="left: 138px;"><span _ngcontent-c1="" class="element__name"> Some Name </span></div>