最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Listen to element visibility in Angular 2 - Stack Overflow

programmeradmin0浏览0评论

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
    }
}

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
    }
}
Share Improve this question asked Mar 28, 2017 at 20:34 NateNate 7,87623 gold badges76 silver badges129 bronze badges 6
  • You should use host property of ponent – Babar Hussain Commented Mar 28, 2017 at 20:38
  • @BabarBilal please develop your answer... – Nate Commented Mar 28, 2017 at 20:53
  • How is it hidden or displayed? The browser doesn't provider no event when an element bees invisible, therefore also Angular doesn't provide that. – Günter Zöchbauer Commented Mar 28, 2017 at 20:55
  • @GünterZöchbauer Like mentioned in the question by using .hidden-sm-up in a parent. – Nate Commented Mar 28, 2017 at 20:58
  • 1 So it's pure CSS. You can only poll by iterating parents and check the display property for hidden or whatever you apply in your CSS. – Günter Zöchbauer Commented Mar 28, 2017 at 21:00
 |  Show 1 more ment

2 Answers 2

Reset to default 6

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 ponent 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.

I found nice blog regarding that. HostListener has visible event. https://netbasal./with-great-angular-ponents-es-great-single-responsibility-5fa37c35ad20

发布评论

评论列表(0)

  1. 暂无评论