One-way and Two-way Data Binding in Angular

Dany Paredes - Jun 7 '21 - - Dev Community

Today I was helping a new guy in angular with differences between the bind data in Angular, because it provides 2 ways to move data to DOM, One-way and two-way data binding it help 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 few ways.

Interpolation

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

<p>{{myproperty}}</p>
Enter fullscreen mode Exit fullscreen mode

Property binding

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

<p [hidden]="myproperty"></p>
<app-username [name]="myproperty"></app-username>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Two-way binding

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

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

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

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

<input [(ngModel)]="name" />
{{name}}
Enter fullscreen mode Exit fullscreen mode

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

Photo by Surface on Unsplash

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player