在Angular 2中收听元素可见性 [英] Listen to element visibility in Angular 2
问题描述
我正在为我的Web应用程序使用Bootstrap和Angular 2(v4).我想听指令中的元素更改可见性.我的元素有一个父元素,可以使用hidden-sm-up
隐藏其子元素,并且每次隐藏或显示时都需要触发一个函数.
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')
并在我的指令中:
@Directive({
selector: '[myDirective]'
})
export class myDirective {
constructor(private element: ElementRef, private renderer: Renderer){
}
ngAfterViewInit(): void{
// listen to visibility change here
}
}
推荐答案
ngDoCheck
在运行更改检测时运行,因此,我认为如果要监视它而不是仅在组件创建时获取一次,它是正确的位置时间:
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;
}
也许有更好的选择,例如某些事件在某处发出,但对于一般情况ngDoCheck
应该可以正常工作.
There might be better option, like some events that are emitted somewhere, but for the general case ngDoCheck
should work fine.
这篇关于在Angular 2中收听元素可见性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!