收听Angular 2中的元素可见性

我为我的webapp使用Bootstrap和Angular 2(v4)。 我想倾听可见性更改指令中的元素。 我的元素有一个可以用hidden-sm-up隐藏它的子项的父项,并且每次隐藏或显示时都需要触发一个函数。

div.hidden-sm-up
   input.form-control(myDirective, type='number')

并在我的指示中:

@Directive({
    selector: '[myDirective]'
})

export class myDirective {
    constructor(private element: ElementRef, private renderer: Renderer){

    }

    ngAfterViewInit(): void{
        // listen to visibility change here
    }
}

当运行变更检测时运行ngDoCheck ,因此我认为如果您想监视它,而不是在组件创建时仅获取一次,它就是正确的地方:

@HostListener('window:resize')
ngDoCheck() {
  this.isVisible = this.element.nativeElement.offsetParent !== null;
}

可能有更好的选择,就像发生在某个地方的某些事件一样,但对于一般情况ngDoCheck应该可以正常工作。

链接地址: http://www.djcxy.com/p/83577.html

上一篇: Listen to element visibility in Angular 2

下一篇: search an element in a repeater containing specific text using protractor