How to effectively utilize Angular signales for managing objects within templates?

187 views Asked by At

In the Angular documentation and most tutorials, you'll often come across examples that store simple types, such as numbers or arrays of objects, which are evidently easy to use in templates:

n = signal<number>(0);
users = signal<User[]>([{ id: 1, username: 'user' }]);

{{ n() }}
<li *ngFor="let user of users()">{{ user.id }}</li>

But what should you do when you have an object stored in a signal?

user = signal<User>({ id: 1, username: 'user' });

Should you access all properties directly from the signal call, or should you wrap everything inside an ng-container for easier access?

{{ user().id }}
{{ user().username }}

vs

<ng-container *ngIf="user() as user">
  {{ user.id }}
  {{ user.username }}
</ng-container>

The second approach seems more readbale, but it may not be suitable for all situations. It also introduces an unessary wrapper, if-clasue and declaration. The first one may seem bloated and inefficient with to smany function calls, even though it could be highly optimized.

So, which method is the preferred and correct way to access objects stored in signals?

1

There are 1 answers

0
OZ_ On BEST ANSWER

The first one will work in "else" branch of the built-in control flow (v17+), the second one is just more readable - the difference in performance should be neglectable, according to Angular team comment.