
Calling count() in a Template Is Fine; Calling getTotal() Isn't
- كاتب موثّق
- Angular 22
محتويات المقال
{{ itemCount() }}, and the review comes back: "No function calls in templates, they run on every change detection." The same reviewer approved {{ total }} last month, where total is a get accessor that loops over every cart line and applies discounts to each one. The rule flagged the cheap call and waved through the expensive one, because it looks for parentheses instead of work.
The common misconception
{{ count() }} is the same mistake as {{ getTotal() }}.
What actually happens
Each check re-evaluates the template
@if conditions) and compares each result with the previous one to decide which DOM nodes to update. Nothing is skipped because it looks like a property: a get total() accessor is a function, so {{ total }} runs it on every check, exactly like {{ getTotal() }}. Since Angular 22, components use OnPush by default, so a component is checked only when there's a reason: a signal its template reads changes, it receives new inputs, or an event fires inside it. But every check still runs every expression.
Reading a signal is a lookup
count() doesn't compute anything. It returns the value the already holds and, because it runs while Angular renders the template, it records that this component depends on count. That record is the reason you call it: when count changes, Angular marks the component for check without any markForCheck() from you. The cost doesn't grow with your data, so reading the same signal in five places of a template is fine. Forget the parentheses and the NG8109 diagnostic warns that {{ count }} doesn't read the value at all.
computed() remembers; a getter recomputes
import { Component, signal } from '@angular/core';import { CurrencyPipe } from '@angular/common';@Component({ selector: 'app-cart-summary', imports: [CurrencyPipe], template: ` <input #note (input)="giftNote.set(note.value)" /> <p>Total: {{ total | currency: 'EGP' }}</p> `,})export class CartSummary { readonly lines = signal<CartLine[]>([]); readonly giftNote = signal(''); // No parentheses in the template, yet it runs on every check get total(): number { return this.lines().reduce((sum, l) => sum + lineTotal(l), 0); }}import { Component, computed, signal } from '@angular/core';import { CurrencyPipe } from '@angular/common';@Component({ selector: 'app-cart-summary', imports: [CurrencyPipe], template: ` <input #note (input)="giftNote.set(note.value)" /> <p>Total: {{ total() | currency: 'EGP' }}</p> `,})export class CartSummary { readonly lines = signal<CartLine[]>([]); readonly giftNote = signal(''); // Runs on first read, then again only when lines() changes readonly total = computed(() => this.lines().reduce((sum, l) => sum + lineTotal(l), 0), );}CartSummary again, and the template re-evaluates total, looping over every line although no line changed. With computed(), the derivation runs the first time total() is read and the result is cached. Angular marks it stale only when a signal it read during the derivation changes, here lines. Each keystroke now reads a cached number. The docs put it plainly: computed signals are lazy and , so expensive derivations like filtering arrays are safe in them.
getVisibleLines() returns this.lines().filter(...), it builds a new array on every check, and a child component that receives it as an input sees a new value each time, because Angular compares inputs with Object.is. An OnPush child is then checked on every pass. A computed() keeps returning the same array until its dependencies change, so the child is skipped.
Pure pipes cache per binding
transform only when its input changes: a different primitive, or a new object reference. That makes pipes the right tool where a computed() is awkward, like formatting each row inside @for:
import { Pipe, PipeTransform } from '@angular/core';@Pipe({ name: 'initials' }) // pure by defaultexport class InitialsPipe implements PipeTransform { transform(fullName: string): string { // runs again only when fullName changes return fullName.split(' ').map((part) => part[0]).join(''); }}{{ user.name | initials }} in a 500-row table, transform runs once per row when the row first renders, then only for rows whose name changes. The same helper called as a method would run 500 times on every check.
{{ count() }} (signal) | ||
{{ total() }} (computed) | ||
{{ getTotal() }} (method) | ||
{{ total }} (get accessor) | ||
{{ name | initials }} (pure pipe) | name changes |
How to apply it in your project
Keep signal reads in templates Read signals directly with count(). Don't copy them into plain fields to dodge the parentheses: a plain field doesn't tell Angular when to update.Hunt for methods and getters that do work Search your templates for method calls and getaccessors that loop, sort, filter or format, and move each one into acomputed().Use pure pipes for per-row transforms When the same transformation runs for every item in @for, write a small pure pipe instead of calling a helper method.Measure before and after Record with the Angular DevTools profiler, pick a change detection cycle, and compare how long each component took.
Key takeaways
Every check re-evaluates every template expression; a method or getter runs its full body each time. count()returns a stored value and registers a dependency, which is how the component knows when to update.computed()recomputes only when a signal it read changes, and returns the same reference until then.Pure pipes cache per binding, which makes them the tool for per-row formatting. Judge a template expression by the work it does, not by whether it has parentheses.
التعليقات (0)