How to optimize Computed Signals: Prevent re-creation for each item after change detection?

Discussão em 'Angular' iniciado por Jonas Hammerschmidt, Janeiro 22, 2025.

  1. I’m using Angular 19 with the new signals API (and OnPush strategy). I have a component that tracks the current URL as a signal, then for each item in an array (e.g., a menu), I create a computed signal to check if it matches the URL. Here’s a simplified version:

    export class MenuComponent {
    url = toSignal(
    this.router.events.pipe(
    filter(e => e instanceof NavigationEnd),
    map(e => e.urlAfterRedirects)
    )
    );

    isActivated(item: MenuItem) {
    return computed(() => this.url()?.startsWith(item.routerLink) ?? false);
    }

    // Template snippet:
    // <li *ngFor="let item of items">
    // <a [routerLink]="item.routerLink" [class.active]="isActivated(item)()">
    // {{ item.label }}
    // </a>
    // </li>
    }


    Question: Every time the template is checked, it calls isActivated(item), which creates a new computed signal instance for each item. I suspect there’s a more efficient way to do this. What’s the recommended pattern or approach to avoid creating a fresh computed for each item every time, while still keeping the application reactive to URL changes?

    Continue reading...

Compartilhe esta Página