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 forhidden
or whatever you apply in your CSS. – Günter Zöchbauer Commented Mar 28, 2017 at 21:00
2 Answers
Reset to default 6ngDoCheck
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