DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Recursive Angular Rendering of a Deeply Nested Travel Gallery
  • 50+ Top Angular Interview Questions and Answers
  • Automated Bug Fixing: From Templates to AI Agents
  • Rediscovering Angular: Modern Advantages and Technical Stack

Trending

  • Stateless vs Stateful Stream Processing With Kafka Streams and Apache Flink
  • Breaking Bottlenecks: Applying the Theory of Constraints to Software Development
  • Intro to RAG: Foundations of Retrieval Augmented Generation, Part 1
  • *You* Can Shape Trend Reports: Join DZone's Software Supply Chain Security Research
  1. DZone
  2. Coding
  3. Frameworks
  4. Don't Use Functions Inside Angular Templates and What to Use Instead

Don't Use Functions Inside Angular Templates and What to Use Instead

To make your app do stuff you need functions, right? It turns out that pipes can actually be more useful in some instances.

By 
han huynh user avatar
han huynh
·
Updated Dec. 28, 18 · Tutorial
Likes (24)
Comment
Save
Tweet
Share
122.1K Views

Join the DZone community and get the full member experience.

Join For Free

The Problem

Let's say we have a list of members using our services. The list shows the first name, last name, and level of membership in our system

Image title

The logic for membership calculating is simply this:

getMemberShipLevel(point: number): String{
    console.info("---getMemberShipLevel---");
    if(point > 900){
      return 'Platinum';
    }else if(point > 700){
      return 'Gold';
    }else if(point > 500){
      return 'Silver';
    }
    return 'Basic';
 }

And in the template, we use this function:

<tbody>
      <tr *ngFor='let member of members; index as i'>
        <th scope='row'>{{i + 1}}</th>
        <td>{{member.firstName}}</td>
        <td>{{member.lastName}}</td>
        <td>{{member.point}}</td>
        <td>{{getMemberShipLevel(member.point)}}</td>
      </tr>
</tbody>

Looks good right? If we open the console, we'll see the getMemberShipLevel function is being called many times (more than the number of rows in the list).

Image title

This is because of the change detection mechanism in Angular. Angular cannot detect whether the result of getMemberShipLevel is changed until it runs the getMemberShipLevel function.

The thing to consider is that the getMemberShipLevel function will be run even though we have the same input data. If the calculation function is more complex and takes time to finish, it'll be a problem of wasting user-machine resource because we have to use resources for calculating the same result.

Solution

What can we do with this? Can we do something like caching the result for a certain input and then next time use the same input to simply return the cached result?

Yes, we can! The pure pipe can help us in this case. Here is how pure pipe works from Angular document:

Angular executes a pure pipe only when it detects a pure change to the input value. A pure change is either a change to a primitive input value (String, Number, Boolean, Symbol) or a changed object reference (Date, Array, Function, Object).

Let's create a custom pipe and move the getMemberShipLevel function to it:

@Pipe({
  name: 'getMemberShipLevel',
  pure: true
})
export class GetMemberShipLevelPipe implements PipeTransform {

  transform(value: number, args?: any): any {
    return this.getMemberShipLevel(value);
  }
  getMemberShipLevel(point: number): String{
    console.info("---getMemberShipLevel---");
    if(point > 900){
      return 'Platinum';
    }else if(point > 700){
      return 'Gold';
    }else if(point > 500){
      return 'Silver';
    }
    return 'Basic';
  }
}

And use it in the template:

<tbody>
      <tr *ngFor='let member of members; index as i'>
        <th scope='row'>{{i + 1}}</th>
        <td>{{member.firstName}}</td>
        <td>{{member.lastName}}</td>
        <td>{{member.point}}</td>
        <!-- <td>{{getMemberShipLevel(member.point)}}</td> -->
       <td>{{member.point | getMemberShipLevel}}</td>
     </tr>
</tbody>

Test it:

Let's reload the page, select 5 items, and check the console. There'll be no output line, that means the calculation results have been cached.

Image title

Conclusion

Use a pure pipe instead of a function in Angular templates.

This only works with primitive input types. If the input is an object, make sure you are providing a new object reference.

This is the source code for the demo https://github.com/truonghan0812/tutorials.

That's it guys, hope it helps!

AngularJS Template

Opinions expressed by DZone contributors are their own.

Related

  • Recursive Angular Rendering of a Deeply Nested Travel Gallery
  • 50+ Top Angular Interview Questions and Answers
  • Automated Bug Fixing: From Templates to AI Agents
  • Rediscovering Angular: Modern Advantages and Technical Stack

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!