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.
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.
There are side effects to using 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With