角度* ng如果绑定到函数 [英] Angular *ngIf binding to function

查看:56
本文介绍了角度* ng如果绑定到函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想问一下* ngIf绑定到函数的返回值.比较* ngIf绑定到属性时,它会有性能开销吗?

I would like to ask about *ngIf binding to function return value. Will it have performance overhead when comparing *ngIf binding to property.

这只是用于询问概念的示例代码,其数据结构比DataService中的复杂.启用标志将保存在地图对象中.这只是一个简单的表达式:

This is only sample code for asking concept, the data structure is complex than that in DataService. The enable flag will be saved in a map object. This is just a simple expression:

在打字稿服务中

export class DataService() {
   private enable: boolean;

   isEnable() {
      return enable;
   }

   getEnableValue() {
      return enable;
   }

   update(flag: boolean) {
      enable = flag;
   }
}

在html中,

<div *ngIf="isEnable()">
    <p> {{ testObject.value }}</p>
</div>

在打字稿中,

isEnable() {
   return this.dataService.isEnable();
}

vs

在html中,

<div *ngIf="isEnable">
    <p> {{ testObject.value }}</p>
</div>

在打字稿中,

isEnable: boolean;
ngOnInit() {
    isEnable = this.dataService.getEnableValue()
}

对于* ngIf ="isEnable",我能理解.但是对于函数绑定,角度检查函数中的属性并监视它的变化吗?有任何性能差异吗?

For *ngIf="isEnable", I am able to understand。 But for function binding,is angular check the property in the function and monitor it changes? Any performance difference?

非常感谢.

推荐答案

从技术上讲,性能没有明显的差异.

Technically speaking there is no noticeable difference in performance.

当Angular编译AOT模板时,它们将转换为JavaScript源代码,并且所有这些单向绑定都将转换为函数.

When Angular compiles AOT templates they are converted into JavaScript source code, and all those one-way bindings are turned into functions.

因此,执行以下任何一项操作时,我的表现都不会明显.

So I there shouldn't be any noticeable performance when doing any of the following.

export class MyComponent {
     public title1: string;

     public get title2(): stirng {
          return this.title1;
     }

     public getTitle3(): string {
          return this.title1;
     }
}

使用以上所有3种方法将获得大致相同的效果.

Use all 3 above would have about the same performance.

使用功能会有副作用.

  • 它打破了模板的枯燥原则
  • 您无法查看模板的复杂程度
  • 函数内部的
  • 性能是隐藏的
  • it breaks the dry principle of a template
  • you can not see how complex a template is
  • performance is hidden inside functions

我还发现您倾向于在模板中做更多的工作.调用函数时,可以更轻松地使用 * ngIf * ngFor 和其他逻辑组件.

I've also found that you tend to do more work in the template. When you call functions it makes it easier to use *ngIf, *ngFor and other logical components.

阅读该组件的源代码时,您将无法获得完整的画面.模板中有很多业务逻辑,而当您阅读模板时,您看不到如何查看模板,因为模板中有很多逻辑.

When you read the source code for the component you don't get the full picture. There is a lot of the business logic being done in the template, and when you read the template you don't see how it will be viewed, because there is a lot logic in the template.

这篇关于角度* ng如果绑定到函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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