1

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.

4

1 回答 1

0

我最终使用setInterval继续检查宽度。

@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);
            }
        }
    }
}
于 2017-02-01T17:57:39.283 回答