user11899717
user11899717

Reputation:

Angular using function inside interpolation {{function()}} what does it mean and is it a good practice

What does using function inside string interpolation mean here?

<p>{{trackTotal()}}</p>   

For any change, even putting some value in input on same page also it is called:

trackTotal()

<input type="text" />

Is it a good practice or bad practice to use it this way?

Upvotes: 0

Views: 2025

Answers (2)

kvetis
kvetis

Reputation: 7331

It depends on what the trackTotal does. Since you did not provide code for it, it is hard to tell.

Generally it is better to have a value stored in a component property and compute it only when it's necessary. But using a function is not bad either, if it only does a small computation. You could also use a pipe instead of the function, though.

If implementation is similar to trackTotal() { return this.data.total } then it's fine to use it. But creating a getter might be a better option.

If it has any side effects, then not.

trackTotal() {
    this.service.startAProcess();
    // or
    return this.total = this.values.reduce((a, b) => a + b);
}

Upvotes: 1

Pandiyan Cool
Pandiyan Cool

Reputation: 6565

Its a bad practice. The change detection in the component will trigger the function call everytime.

To know more about change detection, check this blog https://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html#whats-change-detection-anyways

Upvotes: 0

Related Questions