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.

userName = signal("Anil sidhu")

Since this is a signal, it is accessed like a function.

To make it work with ngModel, a getter and setter are created.


get uName() {
return this.userName();
}

set uName(val: string) {
this.userName.set(val);
}

The getter returns the signal value.

The setter updates the signal value using set().

Now ngModel works like a normal property.

<h1>{{ uName }}</h1>
<input type="text" [(ngModel)]="uName">

Typing in the input updates the signal automatically.


Signal with Object Data

An object signal is created for user data.

userData = signal({
college: 'iet alwar',
email: 'anil@test.com'
})

Getters and setters are created for a single property, not for the whole object.

Getter for college value.

get userCollege() {
return this.userData().college;
}

Setter for college value.

set userCollege(val) {
this.userData.update(item => ({
...item,
college: val
}));
}

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

<h2>{{ userCollege }}</h2>
<input type="text" [(ngModel)]="userCollege">

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.