Angular 4/5/6 Event Binding + Two Way Databinding Simple Example

Angular 4 Event Binding + Two Way Databinding Simple Example

What is Event Binding ?

Event Binding in angular adds an event handler which will be triggered on the added event action.

For example:

<button (click) = “addMe()”> Add Me </button>

 
Here (click) is a click event in angular binded to addMe() method, so when ever user clicks Add Me button then it calls addMe() function in the respective component of angular.

What is Two Way Databinding ?

Two way Databinding is nothing but tightly binding the model and the view variable, so whenever there is a change in the UI view, immediately model also be updated with the change and vice versa.

 

For example:

<input type=”text” [(ngModel)]=”username” >

 

here [(ngModel)] = “username” is a two way databinding and username variable is a variable mapped to this two way databinding.

Below is the example created in angular with both event and two way databinding for easy understanding. Feel free to post your comments in the below comments section.

 

Typescript file:

[html]
import { Component } from ‘@angular/core’;

@Component({
selector: ‘app-root’,
templateUrl: ‘./app.component.html’,
styleUrls: [‘./app.component.css’]
})
export class AppComponent {
techName: string = ”;
techDesc: string = ”;
technologies = [];

addTechName(){
this.technologies.push({
type:’tech’,
techname: this.techName,
techdesc: this.techDesc
});
}
}

[/html]

 

HTML File:

[html]
<div class=”container”>
<div class=”row”>
<h2> Add New Technology </h2>
</div>

<div class=”row”>
<div class=”col-xs-12″>
<label for=”techN”> Enter Technology Name </label>
<input type=”text” [(ngModel)] = “techName” id=”techN”>

<label for=”techD”> Enter Technology Description </label>
<input type=”text” [(ngModel)] = “techDesc” id=”techD”>

<button class=”btn btn-success” (click)=”addTechName()”>Add New Tech</button>

</div>
<div class=”col-xs-12″>
<div *ngFor=”let technology of technologies”>
<p> {{ technology.techname }} | {{ technology.techdesc }} </p>
</div>
</div>
</div>
</div>
[/html]

 

Note: I have also added bootstrap to my angular project. If you like to add bootstrap to your angular please have a quick look at this below post. It is just a 2 simple step process.

How to add Bootstrap 4/5/6 to Angular-CLI project ?

Screenshots:

Angular 4 Event Binding + Two Way Databinding Simple Example

 

Angular 4 Event Binding + Two Way Databinding Simple Example

 

 

 

 

Leave a Reply