Binding with Angular v4 And Above

Hi Readers, I hope you all are doing well and have read my previous tutorials. In my previous article about the Angular Hook Life Cycle, Learn About Angular Component Hook Life Cycle, I have explained the life cycle of components. Today I am here with one more article, Learn Angular 4 Binding which is very important for Angular 4+.

I am going to start with basic things as always. The important question is, what is the use of Binding and why are we using Binding?

What is Binding?

Binding is the concept of Data synchronization which is the process of establishing consistency of data from source to target data and target to source.

Why are we using Binding?

The basic need of Binding is a requirement of data for performing an operation within the application so in this case we can use Binding and perform the required operations that we need for any feature.

Creation of an application that is based on Binding

I already explained in my previous tutorial about application creation using Angular CLI, and with the help of Create Angular Application Using Angular CLI, you can easily create the application. I have also attached here the created application which you can download to easily understand about binding.

For all the available bindings in Angular, I have created an application with the below pages.

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  // Added for Interpolation
  title = 'Binding APP';

  // Added for Property Binding
  btntext = 'Add data';

  // Added for Style Binding
  styleProperty: string = "red";

  // Added for Class Binding
  classproperty: boolean = true;

  // Added for Event Binding   
  secondbuttontext = "new button";

  // Added for Two Way Binding
  inputdata: string = 'My data';

  // Using Event binding update the value of button
  changevalue() {
    this.secondbuttontext = "Update data";
  }
}

app.component.html

<div style="text-align:left;border: 1px solid">
    <h3 style="color:blue">Using Interpolation</h3>
    <!-- Interpolation example: here title are showing using Interpolation -->
    <h2>Welcome to {{ title }}!</h2>
    <hr size="4">
    <h2>One way binding (From Component to template)</h2>
    <!-- One way binding: Type 1: From Component to template -->
    <!-- Property Binding -->
    <h3 style="color:blue">Property Binding Example</h3> <input type="button" [value]='btntext' />
    <h3 style="color:blue">Style binding</h3> <button [style.color]="styleProperty ? 'red' : 'green'">Red</button>
    <h3 style="color:blue">Class Binding</h3>
    <div [class.myclass]="classproperty">Class Heading</div>
    <h3 style="color:blue">attribute binding</h3>
    <table border=1>
        <tr>
            <td [attr.colspan]="1 + 1">One-Two</td>
        </tr>
        <tr>
            <td>1</td>
            <td>2</td>
        </tr>
    </table>
    <hr size="4">
    <h2>One way binding (From template to component)</h2>
    <!-- One way binding: Type 2: From template to component -->
    <!-- Event Binding -->
    <h3 style="color:blue">Event Binding Example</h3> <input type="button" [value]='secondbuttontext' (click)="changevalue();" />
</div>
<hr size="4"> <br>
<h2>Two way binding (Combination of Property and Event Binding)</h2>
<!-- two way binding with property and event binding combination --><span>Input Text: </span>
<input type="text" name="data" placeholder="modal data" [(ngModel)]="inputdata"> <br> <br>
 <span>{{ inputdata }}</span> <br>

Now, I am going to explain the binding. Mainly, we have the following binding in Angular.

Binding Types

One-way Binding (From component to template view)

Interpolation

It's a very common way of binding in Angular. With the help of the Interpolation {{}} sign, we can show the data in the View.

For example

// added for Interpolation
title = 'Binding APP';
<!-- Interpolation example: here title are showing using Interpolation -->
<h2> Welcome to {{ title }}! </h2>

You can see that in the above code, I have added the code <h2> Welcome to {{ title }}! </h2> which shows the title. I have added it in the app.component.ts file as title = 'Binding APP. Here we are using interpolation by which the added titles are showing.

Property Binding

app.component.ts

btntext='Add data';

app.component.html

<!-- One way binding: Type 1: From Component to template -->
<!-- Property Binding -->
<h3 style="color:blue">Property Binding Example</h3>
<input type="button" [value]='btntext' />

As you can see above, the button text value is added in the typescript file, and in HTML we are showing the added value with the help of value property so here we are using property binding.

Style Binding

app.component.ts

// added for Style Binding
styleProperty: string = "red";

app.component.html

<h3 style="color:blue">Style binding</h3>
<button [style.color]="styleProperty ? 'red' : 'green'">Red</button>

As you can see, I have added the styleProperty variable which I have added in the typescript file, and in html we are showing the styles as style. color with the help of value style binding. If styleProperty has value it will show red text in the button otherwise it will show green text with the value text of the button.

Class Binding

app.component.ts

// added for Class Binding
classproperty: boolean = true;

app.component.html

<h3 style="color:blue">Class Binding</h3>
<div [class.myclass]="classproperty">Class Heading</div>

styles.css

.myclass {
    font-size: 28px;
}

As you can see above, I have added the classproperty variable which I have added in the typescript file, and in HTML we are showing the text with added style in the style.css file using class binding. If the class-property variable is true then my class CSS will show with the div text else the css will not apply.

Attribute Binding

app.component.html

<h3 style="color:blue">attribute binding</h3>

<table border="1">
  <tr>
    <td [attr.colspan]="1 + 1">One-Two</td>
  </tr>
  <tr>
    <td>1</td>
    <td>2</td>
  </tr>
</table>

As you can see above, I am using the colspan attribute property of td as [attr. colspan] so here with the help of attribute binding the table cell (td) will use colspan property and the added data will show within two tds.

One-way Binding (From template view to component)

Event Binding

It’s another method of binding in Angular as below.

app.component.ts

// added for Event Binding   
secondbuttontext = "new button";

// Using Event binding update the value of button   
changevalue() {   
  this.secondbuttontext = "Update data";   
}  

app.component.html

<hr size="4"> <br>
<h2>One way binding (From template to component)</h2>
<!-- One way binding: Type 2: From template to component -->
<!-- Event Binding -->
<h3 style="color:blue">Event Binding Example</h3>
<input type="button" [value]='secondbuttontext' (click)="changevalue();"> 
Please click on the button to see the event binding 
<hr size="4"> <br>

As you can see above, I have added the second button text for the button. I have added (click) the change value method which I have defined in the typescript file. When you click on the button the previous button value text will change to new text which is in the changevalue method so here I am using Event Binding. With the help of the event, the button value text will be updated.

Two-Way Binding

It's another type of binding that is mostly used in Angular applications. It’s a combination of Property Binding and Event Binding. For example:

app.component.ts

// added for Two-Way Binding   
inputdata: string = 'My data';

app.component.html

<h2>Two way binding (Combination of Property and Event Binding)</h2>
<!-- Two-Way binding with property and event binding combination -->
<span>Input Text:</span>
<input type="text" name="data" placeholder="modal data" [(ngModel)]="inputdata">

<br>
<br>

<span>{{ inputdata }}</span><br>

As you can see above I have added an input data string variable within the typescript file and in the HTML file, I have used ngModel with both the binding, which means property and event binding. I am showing the input data with interpolation with the span. When the view shows the first time in the application the value of input data will display within input control and span which we have added in the app.componet.ts file

When we add any text with the input control the added text will show with span and within input control so here we are using Two-Way Binding.

When we use ngModel it will run successfully or show an error. Yes, it will show the error because we can use ngModel with FormsModule only so it will show the below error.

Error

Error

We have to use FormsModule within the app.module.ts file to solve the error.

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
// added for ngModel   
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule, FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

When we use FormsModule the ngModel will work properly so with the help of [(ngModel)] we can implement the Two-Way Binding.

Now, according to all the above binding, the application will show the below output when we run as localhost:4200 which is the default.

Output

Output

You need to know more information about Binding. We have a few more types of Property and Event Binding.

Property Binding

1. Element property

<img [src]="myImageUrl">

Here src is the element property that is used to get the URL of the image.

2. Component property

<child-component [childdata]="parentdata"></child-component>

Here we are using @input decorator by which we are passing the parent component value to the child component.

3. Directive property

<div [ngClass]="{active: isActive}"></div>

Here we are using the Built-in directive ngClass which we are using for applying the active class if isActive is true.

Event Binding

1. Element Event

<button (click)="getdata()">GetData</button>

Here click is the element event by which we are using the getdata method.

2. Component Event

<div>
  <!-- Child component -->
  <input [ngModel]="count">
  <button (click)="increment()">+</button>
</div>

Here we are using EventEmitter for updating the value of count which is @Input() so with the help of Component Event we are showing the value of count.

3. Directive Event

It's also another type of Event Binding that we will use with the Directive and Output EventEmitter.

The details about all the above types of Property and Event Binding will be in my later tutorial.

Conclusion

So we can say we have many bindings that we can use with our Angular application and with the help of these we can use the required data according to our requirements.

I hope you liked this -- please share it if you did. I will define the Angular Routing in my later tutorial which is one of the main features in Angular applications.


Similar Articles