簡體   English   中英

如何強制某個功能等待某些事情發生?

[英]How to force a function to wait until something happens?

<div *ngFor="let post of posts">
  <div [innerHtml]="getPostContent(post.content)" #postContentDiv></div>
  <button *ngIf="getPostContentHeight(postContentDiv)">Show more</button>
</div>

職能

getPostContent(content: any): any {
  return this.sanitizer.bypassSecurityTrustHtml(content);
}

getPostContentHeight(postDiv: any): boolean {
  return postDiv.offsetHeight > 50;
}

我有postContentDiv文章(標題,作者,內容等),我想顯示一個按鈕,如果postContentDiv高於50px,則Show more 問題是這一行:

<button *ngIf="getPostContentHeight(postContentDiv)">Show more</button>

正在此行之前運行:

<div [innerHtml]="getPostContent(post.content)" #postContentDiv></div>

影響? getPostContentHeight在由post.content填充之前檢查#postContentDiv高度。 當我從列表所在的組件開始或刷新頁面時,一切都正常,但是當我切換到另一個組件並返回時,該組件不起作用。

##示例##

簡而言之:在另一個修改getPostContentHeight參數的函數之前, getPostContentHeight運行得太快。

組件X是具有帖子列表和視圖的組件。 組件Y是另一個僅用於幫助的組件。

http://localhost:4200/X -我看到Show more按鈕。 當我現在更改為組件Y,然后再次更改為X時,沒有Show more按鈕。 幾秒鍾后,當Angular執行第二次檢查時,它們就會出現。

我建議您使用Google Promises,因為這將使您可以阻止函數啟動,直到一切(完全發生)之前必須發生的一切。

因此,您將獲得以下內容:

 new Promise(etPostContent(post.content)).then(getPostContentHeight(postContentDiv)); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM