Basic Binding In Angular 5 With Example

Binding in Angular

There are some basic types of binding used in Angular 5. I have listed some types of binding below,

  1. Event Binding
  2. Two-way Binding
  3. Template reference variable
Event Binding

There are multiple DOM events that can be used like click, key up, keypress, mouse over etc. Events are simply the actions taken by the user and can be of any type. Event binding is used to handle the DOM action raised by a user. Let’s see a simple example of event bindings.

In app.component.html,

  1. <button (click)="MyEventBind($event)">Event Binding</button>  

In app.component.ts

  1. MyEventBind(e)  
  2. {  
  3.    console.log(e);  
  4.    alert("This is Event Binding in Angular 5.");  
  5. }  

Our output will be,

This is Event Binding in Angular 5.

In the above example, on button (click) or on-click event, we have displayed alert message and logged a mouse event.

You can try this example of event binding for multiple events which are used for multiple operations.

Two-way binding

Two-way binding is an important feature of Angular 5. It automatically reflects the changes in the user interface (UI), i.e., View from Model. Here, we need to use [(ngModel)] or bindon-ngModel to bind the data. It is difficult in other languages to achieve these functionalities. We have to import FormsModules to achieve two-way binding.

Let’s see the below example.

In app.component.html,

  1. <input type="text" [(ngModel)]="txteventbinding">  
  2. <button (click)="Test()">Test</button> 

In app.component.ts,

  1. txteventbinding = '';  
  2. Test()  
  3. {  
  4.    alert(this.txteventbinding);  
  5. }  

Our output will be,

This is sample text

Template reference variable

This shows that the whole element properties can be accessed by using “#” or “ref” keyword.

Let’s see the below example.

In app.component.html,

  1. <input type="text" #text1>  
  2. <button (click)="TemplateTest(text1.value)">Template Test</button>  

In app.component.ts,

  1. TemplateTest(strstring)  
  2. {  
  3.    alert(strstring);  
  4. }  

Our output will be,

This is template text.
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now