简体   繁体   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>

functions 职能

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

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

I have a couple of posts (title, author, content, etc.) I'd like to show button Show more if postContentDiv is higher than 50px. 我有postContentDiv文章(标题,作者,内容等),我想显示一个按钮,如果postContentDiv高于50px,则Show more The problem is this line: 问题是这一行:

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

is being run before this line: 正在此行之前运行:

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

effect? 影响? getPostContentHeight checks #postContentDiv height before it fills up by post.content . getPostContentHeight在由post.content填充之前检查#postContentDiv高度。 All works fine when I start on the component where the list is or when I refresh the page but it doesn't work when I change to another component and go back. 当我从列表所在的组件开始或刷新页面时,一切都正常,但是当我切换到另一个组件并返回时,该组件不起作用。

## Example ## ##示例##

In short: getPostContentHeight runs too fast, before another function which modifies getPostContentHeight argument. 简而言之:在另一个修改getPostContentHeight参数的函数之前, getPostContentHeight运行得太快。

Component X is a component which has the posts list and view. 组件X是具有帖子列表和视图的组件。 Component Y is another component just for help. 组件Y是另一个仅用于帮助的组件。

start at http://localhost:4200/X - I see Show more buttons. http://localhost:4200/X -我看到Show more按钮。 When I change now to component Y and then again to X, there is no Show more buttons. 当我现在更改为组件Y,然后再次更改为X时,没有Show more按钮。 They appear after a few seconds when Angular does second check run. 几秒钟后,当Angular执行第二次检查时,它们就会出现。

I suggest you to google Promises as that's what will allow you to keep a function from starting until anything that has to happen before happened (and completely). 我建议您使用Google Promises,因为这将使您可以阻止函数启动,直到一切(完全发生)之前必须发生的一切。

So you'll have something like: 因此,您将获得以下内容:

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

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

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