Bindings in Angular-Types and Usages

What is Binding?
It defines the connection between the UI of the application( HTML) and the data coming from some business logic through components.

 

Here we will discuss different types of bindings in Angular. basically, there are 3 types of bindings, but there are few variations of it, will discuss all of them.

  1. Property Binding
  2. Event Binding
  3. Two-way Binding

Property Binding

It works one side that is the direction of binding is from component to DOM. Any change in the properties of the component is reflected in the DOM.
In property binding, we define the dom element in the square bracket [] to which the binding should reflect.

<img [src]="imageUrl">


Here src is the dom element and imageUrl is the property that is bind from the component.
Code in the Component file is as below:

... 
 imageUrl:any;
  constructor() { }

  ngOnInit() {
    this.imageUrl="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
  }
...

Once we render the page we can see the image as below:

As you can see the URL value is bind to the src attribute in the img element of html.

Some of the variations of the property binding are:

  • String Interpolation
  • Attribute Binding
  • Class Binding
  • Style Binding

String Interpolation
In string interpolation, the property or field in the component is bind in a special syntax called string interpolation syntax with two curly brackets {{}}.
An example of the same is provided in this article.

Attribute Binding 
Similar to property binding only the main difference here is that we use attributes to reference the dom element. Why we use this approach is because there may come situations where we cannot identify direct DOM elements to bind for some html elements. eg. colspan.In order to bind dynamic values to those fields, we use attribute binding.

Sample code in html and components are as follows:

<table border="1">
    <tr>
        <td> A</td>
        <td> B</td>
        <td> C</td>
    </tr>
    <tr>
        <td [attr.colspan]="colspan"> colspan row</td>
    </tr>
</table>

 

...
export class BooksComponent implements OnInit {

  colspan:number
  constructor() { }

  ngOnInit() {
    this.colspan=3;
  }
}
...

 

When the page renders you can see below the output and value of the colspan bound properly.

 

Class Binding
In class binding syntax is the same as square bracket and we mention the class to be added to the html element as:

<button [class.active]="isActive">Save</button>
Here active is the class name to be added or remove and isActive the property from the component based on which class is added dynamically.
The code in the component is as below:
export class BooksComponent implements OnInit {
  isActive:boolean
  constructor() { }
  ngOnInit() {
    this.isActive=true;
  }
}
We have added a style class in the scss file as below:
.active{
    background-color: red;
}
Once we render the page we can see below style in button, also we can see the class added to the html element.


Style Binding
Functionality is the same as class binding, the only difference is that instead of class we use style, and instead of class name we use CSS styles defined. code in html is as below:

<button [style.backgroundColor]="isActive? 'blue':'grey'">Save</button>
For the same code in the component the page will render as below with inline style added to html element.

Event Binding
In event binding, we bind the event to some function inside the component. So the method of communication is from UI to the component. the syntax of it is that the event is enclosed in round brackets as shown below:
<button (click)="onSave()">Save</button>
In order to access the event object we can pass it as shown below:
<button (click)="onSave($event)">Save</button>
$event is the standard event object in angular. To stop the propagation of the event we can mention the below code in the component function, where $event signifies the event object passed to the function.
$event.stopPropagation();
The component code is as below:
 
export class BooksComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }
  onSave(event) {
    console.log('Button Clicked',event);
    event.stopPropagation();
  }
}
Finally, when we click the button we get the below message in the console.
 
Two-way Binding
The final and most important binding method is two-way binding. Here changes in the property can be passed in both ways from UI to component and vice versa. The syntax for two-way binding is [(ngModel)]="propertyname". In order to use it, we need to import FormsModule to our app.module.ts file
import { FormsModule } from '@angular/forms';
...
imports: [
   ...
    FormsModule
  ]
Code in the html is as below: Here we use keyUp event binding with filtering option which is called Event filtering 
<input [(ngModel)]="email" (keyUp.enter)="onKeyUp()"/>
Code in component is as follows:
export class BooksComponent implements OnInit {
  email="me@example.com"
  constructor() { }
  ngOnInit() {  }
  onKeyUp()
  {
    console.log('Email changed:',this.email);
  }
}
Initially, the value of the email field is bind as me@example.com and once we update it the same property has updated value reflected in the component as well.
The functionality of the two-way binding is clear from below demo video:
Hope you get an idea about different types of bindings and how to use it. Do let us you if you have any clarifications or feedbacks.
 

Building Blocks of an Angular Application - Components and Modules

The basic building blocks of an Angular application are:

  1. Components
  2. Modules

Component

It is the combination of Data, HTML template, and Logic for showing the data.

Component=Data+HTML Template+Logic

Module

Container of a group of related components

There are three steps for creating a component

  • Create a component
  • Register it in a Module
  • Add an element in HTML mark up

We will walk you through each step in creating a component and using it in the angular application.

Creating a Component using Command Line
Command to use:

ng g c Books

ng stands for Next Generation, g stands for Generate, c stands for Component and Books stands for the name of the Component

Tip: When you create a component the naming convention is important. We can use camel casing when typing the name of the component in the command window, and once the component is created each capital letter will be replaced by a dash(-). this is applicable to folder name as well as file names.

Register Component in Module

When you create a component it creates a folder and adds necessary files related to that. It also does the second step of registering the component in the module. this is the advantage of using Angular CLI. if we are creating a component manually then we need to register it by adding the component name in the declaration section inside Module.

Add element in HTML markup

Once the component is registered we can use the selector inside the component to add the HTML mark up in the main file.

Component Structure

 Once we create a component the contents of it will as shown below.

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-books',
  templateUrl: './books.component.html',
  styleUrls: ['./books.component.scss']
})
export class BooksComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }
}
@Component is called a decorator function, and it has selector, templateUrl, styleUrls as you can see from the code above.
  • selector- it is used to identify this component using the html markup. for example, the above component will be called in the main index.html file as below:
<app-books></app-books>
  • templateUrl-it specifies the file path of  the html content used in this component. Mostly it will be inside the same folder. we can also add html content inline in the component.ts file itself, but it depends upon the purpose and use of the component. if you are using inline html, the keyword should be template, and is used is as below
...
template:'<h2>Books Component </h2>
...
  • styleUrls- It specifies the file path of the styles for this component. the style we add inside this css or scss file will reflect inside our component only. we can have multiple css files so it is denoted by an array.
Then we have export class ClassName. the export keyword denotes that this component class can be imported. this same class name we will be adding in the declarations of the module.
The class has a constructor which is used to initialize the values of the class and it is also used to set up DI(Dependency Injection). Constructor is called first when we render a component, so it needs to be kept clean and light for the optimal performance of the application.
The ngOnInit() function is called a Life cycle hook, which is used to execute some action after the component is fully loaded. there are other Life cycle hooks also that we will discuss more in a different article since it is out of the scope of this one.
 
In order to make the component fully working, I am adding one message from ts file.
Below is the code inside books.component.ts file
...
export class BooksComponent implements OnInit {
  message:any;
  constructor() { }

  ngOnInit() {
    this.message="Message from Component ts file!";
  }
...
Below is the code inside books.component.html

The syntax used in the below html is called String Interpolation.

<p>Books Works!</p>
<p>
    {{message}}
</p>
To run the full application enter the below command in the terminal.
ng serve
 
If everything goes well you will see the below message in the browser once you navigate to http://localhost:4200/
Hope you get a basic idea about component and modules in Angular.
 
 

Purpose of Webpack in Angular Application

If you are new to angular please refer to this article to know how to set up your first project in angular.

Webpack is a build automation tool used by angular to bundle the script files and style sheets and minifies them at runtime.
When we run the ng server command to run the angular application we can see a set of files compiled and minified. This bundling process is done using Webpack.

when we make any change in Html, style sheet or script files web pack will automatically rebuild the full application and reloads the web page.

Webpack also injects the compiled files reference to the index.html dynamically.
So a refresh is not required on the page to see new changes and this feature is called Hot Module reloading or Hot Module Replacement (HMR).

How to Create first Angular Project using Command Line Interface ?

Steps Involved are:-

  • Download and install node js. Node provider some tools to build Angular project.
  • Use NPM to install angular CLI. Refer here to Install Angular CLI
  • Command to create a new project in angular
    ng new hello-world

    Below are the screenshots of the project creation process.






  • During setting up of project it will ask for enabling angular routing. enter yes and continue.
  • Also, choose the style sheet format for the project.
  • After the project creation is successful it will try to integrate git with the mail present in the system. if it cannot find a proper git configured email it will ask to enter the name and email id to integrate with git.if you are not using git, you can ignore this step.
  • Finally to run the project type below command
    ng serve
    The default port for angular is 4200.project will be running in URL http://localhost:4200/ after compiling.

Structure of an Angular Application

Below we explain the basic structure of an angular application. We give a brief idea about what is the purpose of each folder and files.

e2e [Folder]
Used for writing end-to-end tests in the application. Mainly used for automated tests that stimulates a user browsing process on a web page.e2e test is done by using a library called Protractor. As an angular developer he doesn't need to worry about this folder, mostly comes in picture when we are doing testing in our application.

-protractor.conf.js [File]
It has all the setting for running test

-tsconfig.json [File]
It has settings for the compiler when running e2e tests.

-src [Folder] > app.e2e-spec.ts [File]
All our test cases are written in this file. The test code is written using Jasmine.

-src [Folder] > app.po.ts [File]
We write code in this file to identify elements on our page.

node_modules [Folder]
It contains all third party libraries which are used for development purpose only. During compiling the contents of this folder are bundled. We will not deploy the node_modules folder to the production server.

src [Folder]
Inside this folder our actual source code is present.

-app [Folder]
Here basic building blocks of angular applications like components and modules are present. Every application has at least one module and one component.

-assets [Folder]
we store all images and static files inside this folder.

-environments [Folder]
We store configuration settings for the different environments in this folder. Mostly it has two files environment.prod.ts,environment.ts

-main.ts [File]
This is the starting point of our application.it bootstraps the main module of the application and then the angular will load this module and the rest of the functionality works from there.

-polyfills.ts [File]
It is a bridging file to fill the gap between features that are supported in browsers and features need for the angular application to work.mainly it imports some javascript.

-styles.scss [File]
We add global styles in this file.

-test.ts [File]
It has settings for the testing environment.

.editorconfig [File]
It contains the settings for the code editor. when working in a team on the same project all developers should have the same setting on this file.

.gitignore [File]
It is used in version control to ignore files when checking out files to the repo.

angular.json [File]
It contains standard configurations for the application.

karma.conf.js [File]
Karma is a test runner in javascript. All settings are present in this file.

package.json [File]
It is a standard file present for all applications. It specifies what all libraries our application is depending upon.it has two sections: devDependencies -dependencies for the developer machine and those libraries are not needed to upload to production, and the other one Dependencies-core libraries needed for the main application.

tsconfig.json [File]
It has settings for the typescript compiler.

tslint.json [File]
It is a static analysis tool for typescript code.it checks the code for readability and functionality errors.

How to install Angular CLI?

To install Angular CLI we need node js in the system .so download the latest stable node js.
Node provides some tools to build Angular projects. It helps to execute Javascript code outside the browser.

After installing node js we use NPM(Node Package Manager) to install third-party libraries. To install Angular CLI.

npm install -g @angular/cli

-g in the command specifies your installing the Angular CLI globally.

To check if the installation is successful.

ng --version

Angular CLI screen shot

What is Angular?

Angular is basically a framework for building client applications using HTML, CSS, Javascript, or Typescript.

Angular itself is written using Typescript. When compiling angular application transpiles to Javascript code. Transpiling is a process of converting the typescript code to javascript.

Need for Angular
When we build a complex application using Javascript, it is very difficult to structure, maintain, and test the application. To address these issues we use modern front end frameworks like Angular, React or Vue.js

Benefits

  • Helps to have a clean structure for application
  • Easy to Unit test
  • Reusable Code
  • Traditional javascript are difficult to manage.

The architecture of Angular Application
The angular application works in front only. Data storing is not the headache of angular. It is the back-end service that helps in data storing. Angular uses API(Application Programming Interface) to interact with backend.

First, you can install the typescript and then start setting up your first angular project
Install typescript
Setting up your first Angular Project

If you face any issue during the set up of your angular application, kindly drop in the comments section.