Angular *ngIf binding to function

2019-08-31 06:05发布

问题:

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

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:

In typescript service

export class DataService() {
   private enable: boolean;

   isEnable() {
      return enable;
   }

   getEnableValue() {
      return enable;
   }

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

In html,

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

In typescript,

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

vs

In html,

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

In typescript,

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

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?

Thanks a lot.

回答1:

Technically speaking there is no noticeable difference in performance.

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;
     }
}

Use all 3 above would have about the same performance.

Downsides

There are side effects to using functions.

  • it breaks the dry principle of a template
  • you can not see how complex a template is
  • performance is hidden inside functions

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.



标签: angular