Listen to element visibility in Angular 2

I'm using Bootstrap and Angular 2 (v4) for my webapp. I would like to listen to an element in a directive for visibility changes. My element has a parent that can hide its children with hidden-sm-up and I need to trigger a function each time it is hidden or displayed.

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

and in my directive:

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

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

    }

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

ngDoCheck is run when change detection is run, therefore I think it's the right place if you want to monitor it instead of just get it once at component creation time:

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

There might be better option, like some events that are emitted somewhere, but for the general case ngDoCheck should work fine.

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

上一篇: Selenium如何批量许多isElementDisplayed调用?

下一篇: 收听Angular 2中的元素可见性