Dany Paredes
Dany Paredes | Javascript / Web

Dany Paredes | Javascript / Web

One-way and Two-way Data Binding in Angular

One-way and Two-way Data Binding in Angular

Dany Paredes's photo
Dany Paredes
·Jun 7, 2021·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

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>

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>

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, 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 { }

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}}

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

Photo by Surface on Unsplash

 
Share this