Home Courses Two Way Data Binding in Angular - ngModel vs Signals

Two Way Data Binding in Angular - ngModel vs Signals

Two-Way Data Binding in Angular

Two-way data binding means data stays synced between the TypeScript file and the HTML file.

If data changes in HTML, it updates in TypeScript.

If data changes in TypeScript, it updates in HTML.


Two-Way Data Binding with Signals

A signal is created in the TypeScript file.

userData = signal({
name: "anil sidhu",
age: 25,
email: "anil@test.com"
})

The signal data is displayed in HTML using interpolation.

<h1>{{ userData().name }}</h1>


Updating Signal Data from Input

Input fields are used to update signal values.

<input
type="text"
[value]="userData().name"
(input)="updateUserData('name', $event.target.value)"
>

The input event sends the updated value to a function.


Updating Object Inside Signal

A single function is used to update any property of the object.

updateUserData(key: string, val: string) {
this.userData.update(item => ({
...item,
[key]: val
}))
}

The update() method creates a new object and updates only the required property using a dynamic key.


Updating Multiple Fields Using Same Function

The same function updates name, age, and email.

<h1>{{ userData().age }}</h1>
<input
type="text"
[value]="userData().age"
(input)="updateUserData('age', $event.target.value)"
>

<h1>{{ userData().email }}</h1>
<input
type="text"
[value]="userData().email"
(input)="updateUserData('email', $event.target.value)"
>

Each input updates only its related field.


Result

When the user types in any input:

  1. The signal updates
  2. The UI updates automatically
  3. Data stays synced between HTML and TypeScript

This is two-way data binding using signals and objects.


Interview Explanation (Simple)

Two-way data binding means when data changes in HTML, it updates in TypeScript, and when data changes in TypeScript, it updates in HTML automatically.

Share this lesson: