DEV Community

Chukwuma Anyadike
Chukwuma Anyadike

Posted on

Angular Data Binding Demo

Here I am demonstrating data binding in a small application. Data binding automatically keeps your page up-to-date based on your application's state (direct quote from the Angular docs). Essentially, data binding makes our applications more dynamic and interesting. There are two broad categories of data binding in Angular. There is one-way data binding and two-way data binding. One way data binding can be categorized on whether it is data source to view target (source to view) or view target to data source (view to source).

One-way data binding

Interpolation: source to view. Double curly brace syntax is used like this {{valueToBeInterpolated}}.

//one-way data binding, source-to-view: interpolation

//app.component.ts
title = 'Data Binding Demo';

//app.component.html
<h1>{{title}}</h1>
Enter fullscreen mode Exit fullscreen mode

Property binding: source to view. Square bracket syntax used like this [property]='someVariable'.

//one-way data binding, source-to-view: property binding

//app.component.ts
currentImage = 'https://someImageURL';
isDangerous = false;

//app.component.html
<img [src]="currentImage">
<h2 [style.color]="isDangerous ? 'red' : 'blue' ">{{isDangerous ? 'Warning Danger!' : 'It\'s All Good!'}}</h2>
Enter fullscreen mode Exit fullscreen mode

Event binding: view to source. The event binding syntax uses the paretheses like this (event)='someFunction()'.

//one-way data binding, view-to-source: event binding

//app.component.ts
toggleMessage() {
   this.isDangerous = !this.isDangerous;
};
toggleImage() {
   this.currentImage = this.currentImage===this.dataBindingImage1 ? this.dataBindingImage2 : this.dataBindingImage1
};

//app.component.html
<button mat-raised-button (click)="toggleMessage()">Toggle Alert</button>
<button mat-raised-button (click)="toggleImage()">Toggle Image</button>
Enter fullscreen mode Exit fullscreen mode

Two-way data binding: source to view and view to source.

The syntax is [(ngModel)]="inputText". This is also known as 'banana in a box' syntax.

//two-way data binding, view-to-source and source-to-view

//app.component.ts
inputText = '';

//app.component.html
<input [(ngModel)]="inputText">
Enter fullscreen mode Exit fullscreen mode

Here is a nice demo which demonstrates these principles. Just press play. For more information about data binding: Data Binding In Angular. The code for this demo is available here: Data Binding Demo. Happy Coding.

Top comments (0)