从角度模板多次调用方法 [英] Multiple times method calling from angular template

查看:56
本文介绍了从角度模板多次调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在模板中使用方法来调用函数,该函数返回 boolean 值.问题是该函数被调用超过 6 次.之后我使用 changeDetectionStrategy.onPush 将调用次数减少到 2 次.下面是我的代码

I am using method inside a template to call the function, that returns boolean value. The issue is that the function is called more than 6 times. After that I used changeDetectionStrategy.onPush which reduced the calls to 2 times. Below is my code

HTML

<div *ngIf="(checkboolObs(check$)) | async"></div>

TS

check$: Observable<service> = this.data.getresponse();

ngOnInit() {
  this.checkboolObs();
}
checkboolObs(style):boolean {
  return somestyleIDS.includes(style.component)
}

如果找到该值,则返回 true,但它被多次调用,我只需要调用一次.这背后的原因是因为 checkboolobs() 在导航时有时不会被触发,这就是我从模板调用此方法的原因.

If the value is found it returns true, but it is called several times i need to call it only once. The reason behind this is because checkboolobs() is not triggered some times while navigating that's why I am calling this method from the template.

推荐答案

这是正常的,因为每次调用更改检测周期时,它都会评估模板并且您的函数是其中的一部分,因此该函数将重新评估(再次调用).

This is normal as every time the change-detection cycle is called it will evaluate the template and your function is part of it, so the function will be re-evaluated(called again).

简要说明 Angular 中的变更检测是如何工作的

A brief explanation of how does the change detection work in Angular

想象一下,每次有一个事件,这可能会导致任何变化(例如点击,一些时间间隔正在做某事,ajax 调用)Angular 使用模板并重新评估它开箱即用(在其他单词更新 HTML).

Imagine that each time there is an event, that might cause any change (for example clicks, some time intervals are doing something, ajax calls) Angular takes the template and re-evaluates it for you out of the box (in other words updates the HTML).

当您使用 onPush 策略时,您基本上是在告诉 angular 停止侦听任何提到的更改,因为您将负责在发生更改时通知框架.** 免责声明我们有 |async 可以在模板中使用,它可以很好地与 onPush 策略配合使用,如果您的输入更改通过引用更改检测将被触发,但正如我所说,这是一个简短的解释.

When you use the onPush strategy you are basically telling angular to stop listening for any of the mentioned changes because you will be the one in charge of telling the framework when a change has occurred. ** Disclaimer we have the | async that can be used in templates and it will work fine with the onPush strategy and if your inputs change by reference change detection will be triggered, but as I said this is a brief explanation.

所以你可以做的事情是(我假设你是从 check$ observable 中获取 ID)

So the thing that you can do is (i assume that you are getting the ids from the check$ observable)

myCheck$ = this.check$.pipe(map(arrayOfIds => arrayOfIds.includes(style.component)))

然后在模板中使用 myCheck$|async.

and then use myCheck$ inside your template with |async.

如果这不起作用,请更详细地解释您的用例.

If this doesn't work please explain in more detail your use case.

这篇关于从角度模板多次调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆