问题
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