Two-Way Binding [()] in Angular Tutorial

beginner
6 min

Two-Way Binding [()] in Angular Tutorial

Welcome back to CodeYourCraft! Today, we're diving deep into the concept of Two-Way Binding. This powerful feature of Angular allows data to flow seamlessly between the model (JavaScript code) and view (HTML template).

Understanding Two-Way Binding

Two-Way Binding is a feature that automatically synchronizes the data between the component's class and the corresponding template. In simpler terms, any changes made in one side will be reflected on the other side. 🎯

Why Two-Way Binding?

Two-Way Binding makes our life easier by keeping the model and view in sync. This saves us from writing code to update the view every time the data changes, or vice versa. It's a key feature that makes Angular a great choice for building user interfaces. 💡

Setting Up Two-Way Binding

To use Two-Way Binding, we need to use Square Brackets [] with the property we want to bind.

Let's create a simple example to understand this better.

Example 1: Two-Way Binding with a Simple Property

typescript
import { Component } from '@angular/core'; @Component({ selector: 'app-two-way-binding', template: ` <h2>Name: {{ name }}</h2> <input [(ngModel)]="name" type="text"> ` }) export class TwoWayBindingComponent { name = 'John Doe'; // This is our data model }

In the above example, we have a name property in our component's class. We are binding this property to the input field in the HTML template using [(ngModel)]. This creates a Two-Way Binding.

Now, if you change the input field, the name property in the class will be updated. Similarly, if you change the name property in the class, the input field's value will be updated.

Advanced Two-Way Binding

Two-Way Binding can be used with complex objects and arrays as well. Let's see an example.

Example 2: Two-Way Binding with an Array

typescript
import { Component } from '@angular/core'; @Component({ selector: 'app-two-way-binding-array', template: ` <ul> <li *ngFor="let item of items; let i = index"> {{ item }} <input [(ngModel)]="items[i]" type="text"> </li> </ul> ` }) export class TwoWayBindingArrayComponent { items = ['Item 1', 'Item 2', 'Item 3']; // This is our data model }

In this example, we have an array items in our component's class. We are binding each element of this array to an input field in the HTML template using [(ngModel)]. Now, if you change any input field, the corresponding array element will be updated, and vice versa.

Quiz Time!

Quick Quiz
Question 1 of 1

What does Two-Way Binding do in Angular?

We hope you enjoyed learning about Two-Way Binding in Angular! Join us next time as we continue to explore the exciting world of Angular. 📝

Remember, practice makes perfect! Try implementing these examples in your own projects to get a better understanding of Two-Way Binding. Happy coding! 🎯 🚀