问题描述
我有一个(旋转木马)组件,需要检查元素的宽度.
I have a (carousel) component that needs to check the width of an element.
在浏览器中:我可以调用ngAfterViewInit
并从@ViewChild
手柄获取宽度.但是,当它由Universal渲染时,其宽度为0
.
In the browser: I'm able to call ngAfterViewInit
and get the width from the @ViewChild
handle. But when it's rendered by Universal its width is 0
.
这是因为仍会显示通用生成的dom,但浏览器生成的dom(我的句柄所指向的)位于文档片段内或未显示.
This is because the universal-generated dom is still displayed but the browser-generated dom (where my handle is pointing to) is either inside a document fragment or just not displayed.
ngAfterContentChecked
和ngAfterViewChecked
可以解决此问题,但我不希望它继续运行.
ngAfterContentChecked
and ngAfterViewChecked
can solve the issue, but i don't want it to keep running.
我认为在交换dom之后,我需要一个生命周期挂钩.
I think i need a lifecycle hook for after the dom is swapped.
推荐答案
我最终使用setInterval
继续检查宽度.
I ended up using setInterval
to keep checking for the width.
@Component({
selector: 'my-component',
template: `<div #child></div>`
})
export class MyComponent {
@ViewChild('child') childEl: ElementRef;
constructor( Inject('isBrowser') private isBrowser ){}
doTheThing() {
// do the thing you wanted to do
}
ngAfterViewInit() {
if( this.isBrowser ){
if( this.childEl.nativeElement.clientWidth > 0 ){
this.doTheThing();
} else {
let interval = setInterval( () => {
if( this.childEl.nativeElement.clientWidth > 0 ){
this.doTheThing();
clearInterval( interval );
}
}, 10);
}
}
}
}
这篇关于检查Angular Universal渲染的组件的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!