Check width of component rendered by Angular Universal

柔情痞子 提交于 2019-12-11 06:17:57

问题


I have a (carousel) component that needs to check the width of an element.

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.

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 and ngAfterViewChecked can solve the issue, but i don't want it to keep running.

I think i need a lifecycle hook for after the dom is swapped.


回答1:


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


来源:https://stackoverflow.com/questions/41978500/check-width-of-component-rendered-by-angular-universal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!