Signals Getter & Setter - Two Way Binding with ngModel & signals
Getters and Setters with Angular Signals
Getters and setters are functions used to get and set values of a property.
They help in controlling how a value is read and updated.
When using signals in Angular, ngModel cannot be used directly with signals.
To use ngModel for two-way binding with signals, getters and setters are required.
Simple Signal without Object
A signal is created for a username.
Since this is a signal, it is accessed like a function.
To make it work with ngModel, a getter and setter are created.
The getter returns the signal value.
The setter updates the signal value using set().
Now ngModel works like a normal property.
Typing in the input updates the signal automatically.
Signal with Object Data
An object signal is created for user data.
Getters and setters are created for a single property, not for the whole object.
Getter for college value.
Setter for college value.
update() is used because the signal contains an object.
The old object is copied and only the required property is changed.
Using Object Getter and Setter in HTML
When the input value changes, the object signal updates correctly.
Important Notes
Setter should not return anything.
For object signals, always update a specific property, not the full object.
set() is used for simple signals.
update() is used for object signals.
Getters and setters make ngModel work with signals.