简体   繁体   English

Angular 如何等待组件重新渲染

[英]Angular how to wait for component re-render

I have a function that updates the value of a property of the component.我有一个 function 更新组件属性的值。 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.但由于视图尚未更新,框为 null。我可以执行 setTimeout,但对我来说这似乎是一个糟糕的解决方案。 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.在 angular 中使用原生 DOM 元素是个坏主意。

You do not need to wait for the re-render, you can have your div get its color by using a variable.你不需要等待重新渲染,你可以让你的 div 通过使用一个变量来获得它的颜色。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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