简体   繁体   中英

Angular how to wait for component re-render

I have a function that updates the value of a property of the component. This property is used in the template so when it updates the component re-renders. But I want to run the next code only after the re-render is done. How do I do this.

...
<div *ngIf="showBox"></div>
...
someFunction(): void {
    // update property
    showBox = true;
    // set color
    boxEl.nativeElement.style.color = white;
}

But since the view hasn't updated the box is null. I can do a setTimeout but I that seems a bad solution to me. Is there some other way I can wait for re-render and then continue the execution?

Playing with native DOM elements in angular is a bad idea.

You do not need to wait for the re-render, you can have your div get its color by using a variable.

<div *ngIf="showBox" [style]="boxStyle"></div>

//component.ts
boxStyle = {};
someFunction(): void {
    // update property
    showBox = true;
    // set color
    this.boxStyle.color = "white";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM