It is good practice to use signals in templates and bad practice to use methods.

But signals and methods?

Example (using the get method from Map):

userStatuses: WritableSignal<Map<string, string>> = signal(new Map([ ['Alice', 'offline'], ['Bob', 'online'] ])); <div *ngIf="userStatuses().get('Alice') === 'offline'" class="offline-message"> ⚠️ **ALERT:** Alice is currently offline! </div> 

It's better to use a computed signal like:

isAliceOffline = computed(() => { const status = this.userStatuses().get('Alice'); return status === 'offline'; }); <div *ngIf="isAliceOffline()" class="offline-message"> ⚠️ **ALERT:** Alice is currently offline! 

Which approach performs best and why?

3 Replies 3

Whether it is a function that uses a signal or a computed method or you write the logic directly on the HTML using the signal: When the signal value changes, the related conditions are re-evaluated.

Behavior wise all three do the same thing.


The main difference is logic written in the DOM cannot be unit tested, while methods/derived state can be unit tested, as per my understanding.

Is strange using signals with *ngIf directive, use control flow syntax @if; Also for clarity in your template you can use @let personIsOffline = isAliceOffline().

  • Is better approach the computed to evaluate the status ***** === 'offline'.

Take considerations, the computed will be executed once.

of course signal approach is better, the main reason is the performance, just add console log into method and signal and compare the repetition of that, you will notice that method is running multiple times unnecessary, while the computed signal is aware of dependencies and only run again when one of the dependencies is changed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.