Understanding One-Way and Two-Way Data Binding in Angular

Understanding One-Way and Two-Way Data Binding in Angular

Data Binding in Angular: A Beginner's Guide

Today I was helping a new guy in angular with differences between the bind data because it provides 2 ways to move data to DOM, One-way and two-way data binding. It helps us to build dynamic apps.

It binds the data from our component to the DOM, unidirectional from component to view or view to the component, in a few ways.

Interpolation

The interpolation is used with {{myproperty}} in the DOM.

<p>{{myproperty}}</p>

Property binding

Add brackets around the property []like hidden angular bind the property for DOM elements or components.

<p [hidden]="myproperty"></p>
<app-username [name]="myproperty"></app-username>

Event binding

Angular understand bind events using parentheses like (click) for DOM element or (userSelected) components event trigger.

<button (click)="close()">Close window</button>
<app-logout (logout)="hideDashboard()"><app-/logout>

Two-way binding

Angular two-way data binding is bi-directionally communication using the ngModel directive; it is part of FormsModule from @angular/forms, and it needs to be imported in your app.module.ts

import { FormsModule } from "@angular/forms";
 @NgModule({ 
   imports: [BrowserModule, FormsModule], 
   declarations: [ AppComponent], 
   bootstrap: [AppComponent] 
}) 
export class AppModule { }

Using the directive [(ngModel)] with combination of square brackets and parentheses of the event binding, the ngModel connect our property to changes.

My example links the property name with changes in input but can be used in a select, checkbox, or other DOM elements.

<input [(ngModel)]="name" />
{{name}}

You can see demos: https://stackblitz.com/edit/angular-ivy-9eepqg

Photo by Surface on Unsplash