Binding in Angular


Data Binding in Angular means bind the data in component's HTML file from type script file. We can get and set DOM values dynamically using Data Binding.

Data binding in Angular is either one-way or two-way.

Types of Binding available in Angular-

  • Interpolation
  • Property Binding
  • Two-Way Binding
  • Event Binding

Interpolation

Interpolation uses double curly braces {{ .... }}. It is a one-way binding.

Suppose, we have some data available in component class file which we got via some API.

data = ["one","two","three"];

Now, we have to present this data on HTML. That's the usual task we do with the data.

To display all values -

{{data}}

If you want to print the available values one by one

<ul *ngFor="let prd of data">
<li>{{prd}}</li>
</ul>

{{20+30}}

Above expression will print 50 on screen.

Property Binding


It is a one-way binding used to bind a property of DOM element.

Component class file -

title="Hello World";

Component HTML file -

<h1 [textContent]="title"></h1>

One major example for property binding is

<img [src]="imgURL"/>

Example -

Component class file-

value1 = "Welcome to <b>Angular</b> property binding <i>demo.</i>";

Component HTML file-

<span [innerHtml]='value1'></span>

Two-way Binding

Any changes made in view will reflect in component typescript file.
ngModel directives is used to implement two-way data binding in Angular.

Syntax to implement two-way binding in Angular -

[(ngModel)]="Value"

<input type="text" [(ngModel)]="value">
You are typing {{value}}

Component class file -

userName:string="Ram";

Component HTML file -

<input [ngModel]="userName" (ngModelChange)="userName = $event">
<p>Hello {{userName}}!</p>

Event Binding

Event Binding in Angular is used to handle the events from HTML page. For eg - Button Click.

Component class file -

<button (click)="ShowAlert()">ShowAlert</button>

Component HTML file-

ShowAlert()
{
alert('You clicked on button');
}

In case we want to use parameter in event binding, follow below sample code.

Component class file -


data = ["one","two","three"];
ShowValue(prdValue)
{
alert('You selected--' + prdValue);
}

Component HTML file -

<ul *ngFor="let prd of data">
<li>
<a (click)="ShowValue(prd)">{{prd}}</a></li>
</ul>


Hope you like this blog.
Please share this blog on social media and give your feedback in comment box below.

You may like other blogs -

Interview Questions and Answers Series -

MVC Interview Questions and Answers
Web API interview questions and answers

Keep following - SharePointCafe.Net

Prev - Angular CRUD Example with ASP.Net Web API
Next - Route Guards in Angular

Comments

Popular