What I\'m Doing
I have a component that hides/shows using *ngIf
based on a simple Boolean. When the component becomes visible I want to app
This question is fairly old, and the current solution may not have been available at that time.
The setTimeout()
method is perfectly viable, but has a significant downside. If you just set a class to position an element, like I did, you get a jumpy result, since the code is executed after the angular loop.
Using ChangeDetectorRef
produces a result that does not jump.
So instead of this:
class Foo {
public isDisplayed = false;
constructor(@Inject(ElementRef) private elementRef: ElementRef) {
}
public someMethod(): void {
this.isDisplayed = true;
setTimeout(() => {
const child = this.elementRef.nativeElement.querySelector('.child-element');
// ...
});
}
}
You could do this:
class Foo {
public isDisplayed = false;
constructor(@Inject(ElementRef) private elementRef: ElementRef,
@Inject(ChangeDetectorRef) private changeDetectorRef: ChangeDetectorRef) {
}
public someMethod(): void {
this.isDisplayed = true;
this.changeDetectorRef.detectChanges();
const child = this.elementRef.nativeElement.querySelector('.child-element');
// ...
}
}