Using Signals with Objects
Initialize the Signal:
typescripimport { signal } from '@angular/core'; const userSignal = signal<{ name: string; age: number }>({ name: 'John', age: 30 });
Updating the Signal:
Instead of mutating the existing object, create a new one:
typescriptfunction updateUser(newName: string, newAge: number) { userSignal.set({ ...userSignal.get(), name: newName, age: newAge }); }
Using Signals with Arrays
Initialize the Signal:
typescripconst itemsSignal = signal<string[]>(['Item 1', 'Item 2']);
Updating the Array:
Use methods like
concat
,filter
, ormap
to create a new array instance:typescrifunction addItem(newItem: string) { itemsSignal.set([...itemsSignal.get(), newItem]); } function removeItem(itemToRemove: string) { itemsSignal.set(itemsSignal.get().filter(item => item !== itemToRemove)); }
Key Points
- Immutability: Always return new instances of objects or arrays instead of modifying existing ones.
- Performance: This approach can help with change detection and performance, as Angular can efficiently track changes when references change.
- Readability: This method maintains clarity in your code, making it easier to understand how state changes occur.
By following these principles, you can effectively manage state in Angular applications using Signals while maintaining best practices for immutability.
No comments:
Post a Comment