How to do data binding in Angular 5 ? (Part 5)


In this post we will see how to do data binding in two ways using angular. For this functionality we will do following task

1. Creating an array to store the Emp record.
2. add a default Emp record to Emp array.
3. Creating the Emp properties in typescript
4. Creating a method for saving the Emp record

Step 1 : Now we will go the Emp.Component.ts file and add all required code like this

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

// Emp class in typescript
export class Emp {
  empId: number;
  emailId: string;
  mobileNum: number;
  address: string;

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

//Initalization of Emp properties
export class EmpComponent implements OnInit {
 
  empId: number;
  emailId: string;
  mobileNum: number;
  address: string;
  emps: Emp[];

// Adding the default value to emp array 
  constructor() {
    this.ClearEmpData();

    let defaultEmp: Emp = {
      empId: 2000,
      emailId: "Chandradev@gmail.com",
      mobileNum: 9241503288,
      address: "Bangalore"
    };
    this.emps = [defaultEmp]; 
  }
  ngOnInit() {
  }
  
  //Storing the value in Emp Array
  CreateEmp(){
    let newEmp : Emp= {
      empId:this.empId,
      emailId:this.emailId,
      mobileNum:this.mobileNum,
      address:this.address
    };
    this.emps.push(newEmp);

    this.ClearEmpData();
  }

  // This is for clearing the Emp values 
  private ClearEmpData() { 
    this.empId = null;
    this.emailId = '';
    this.mobileNum = null;
    this.address = '';
  }
}

Step 2: Go to the Emp.Component.html file write the data binding code like this

<div>
    <fieldset>
        <legend>  <b> Emp Details</b></legend>
       <ul *ngFor="let i of emps" >
          <span> EmpId: {{i.empId}} <br> </span>
          <span>Emp EmailId: {{i.emailId}} <br> </span>
          <span> Emp Mobile Num: {{i.mobileNum}} <br></span>
          <span> Emp Address: {{i.address}} </span>
       </ul>
    </fieldset>
 
</div>


<div>
    <fieldset>
        <legend>  <b> Emp Entry Screen with two way data binding demo</b></legend>
        <label> {{ empId }} </label>
<div>
 <b>EmpId:</b>   <input [(ngModel)]="empId" placeholder="enter empId">
</div>
<br>
<label> {{ emailId }} </label>
<div>
    <b>Email Id:</b>   <input [(ngModel)]="emailId" placeholder="enter emp EmailId">
</div>
<br>
<label> {{ mobileNum }} </label>
<div>
    <b>Mobile Number:</b>  <input [(ngModel)]="mobileNum" placeholder="enter mobile Number">
</div>
<br>
<label> {{ address }} </label>
<div>
    <b>Emp Address:</b>   <input [(ngModel)]="address" placeholder="enter address">
</div><br>
<br>
<button class="btn" (click)="CreateEmp()"> Save </button>
                      
</fieldset>
 
</div>

in the above code we saw that we are displaying the data from array using *ngFor angular loop. We have also create a form for accepting the input and adding in Emp array.

>> We have use [(ngModel)] directive for doing two way data binding.
>> 2 curly braces {{ }} are used to bind values to view or template
>> (click) is used to add click handler

Step 3: Go to the app.module.ts file and write the code to import FormsModule as give below image

Step 4: Now save and compile the code in Visual studio code.

How to create components in angular 5 using Angular CLI ? (Part 4)


If you are working with Angular 5 using visual studio code, then there is very simple approach to create the component using Angular CLI.

Step 1: Go to the Visual Studio Code Terminal and type ng g c emp
or ng generate component Emp. Then it will create the component for you

Now we will do some coding in Emp Component for displaying data in View

Step 2: Go to the emp.component.ts and create the Emp class and add some value for Emp properties like this

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

export class Emp 
{
  empId: number;
  emailId :string;
  mobileNum:number;
  address :string;

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

export class EmpComponent implements OnInit {
emp:Emp={
  empId:2000,
  emailId:"Chandradev@gmail.com",
  mobileNum: 9241503288,
  address: "Bangalore"
}
  constructor() { }
  ngOnInit() {
  }

}

Step 3: Go to the emp.component.html and write the code for binding the Emp Class like this


<div>
    <fieldset>
        <legend>  <b> Emp Details</b></legend>
        <h4> EmpId: {{emp.empId}} </h4>
        <h4> Emp EmailId: {{emp.emailId}} </h4>
        <h4> Emp Mobile Num: {{emp.mobileNum}} </h4>
        <h4> Emp Address: {{emp.address}} </h4>
    </fieldset>
 
</div>

Step 4: Now we will go to the app.component.ts and imports the emp component like this
import { EmpComponent } from ‘./emp/emp.component’;

Complete code is like this

import { Component } from '@angular/core';
import { EmpComponent } from './emp/emp.component';

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


export class AppComponent {
  title = 'Angular 5 Demo';
}

Step 5: Now go to the app.component.html and inject the Emp Selector like this


<div>
  Welcome to {{title}}
  <br>
  <app-emp></app-emp>
</div>

Now save and compile the code you will get output like this

What is the component in Angular 5 ? (Part 3)


Components are the building blocks of angular application. Technically components are the typescripts class which is composed of the following 3 things

Template: This is used to render the view for the application.

Class: This typescript class which contains properties and methods which one will be used in view.

Decorator: Decorator adds metadata to the class to make it as component.

Basic structure of components as given below

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

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

How to create our own component for Emp detail and display it in View ?

Step 1: Go to the app.component.ts file and Create the Emp class having required property and assign the value in AppComponent class as given below

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

// create Emp class 
export class Emp
{
  name:string;
  address :string;
  empId: number;
}

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


export class AppComponent {
  emp:Emp = {
    empId: 1000,
    name: ' Chandradev ',
    address:' Bangalore '

  }
}

Step 2: Go to the app.component.html file and write the binding code like this

<div>
    <fieldset>
        <legend>  <b> Emp Details</b></legend>
        <h4> EmpId: {{emp.empId}} </h4>
        <h4> Emp Name: {{emp.name}} </h4>
        <h4> Emp Address: {{emp.address}} </h4>
    </fieldset>
 
</div>

Step 3 : Now save and run the application, you will see the following output

Angular 5 Project Structure (Part 2)


Angular project is the well designed project structure. In this post we will see what are the project structure of angular 5.

The main part of project structure as given below

1. Package.json

>> It comes from traditional nodejs project and it defines all the npm based dependencies , dev-dependencies and npm scripts etc required for the angular project.

2. tsconfig.json

>> This is the root directory for the typescript project. It is also used to define different typescript compilation related options.

3. angular-cli.json

>> This file is used by @angular/cli tool which is used to automate the angular workflow by automating different operations related to development and testing of angular apps. .angular-cli serves as a blueprint to the @angular/cli tool.

4. Src

>> It is the main part of angular project, where we will write the code.
In the src directry we will the following files as given below

1. app:

>> This is the directory where we will define the building block of our angular project like Modules,Components,Services etc.

2. assets:

>> this directory contains all the static assets of our app like images etc.

3. Environments :

>> environments directory hold our environment specific settings , e.g. different configuration files for development , testing and staging etc.

4. Index.html

>> It is the landing page where our angular app bootstraps. It also contains app-root selector which comes from angular app.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>MyApp</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
</body>
</html>

5. main.ts

>>Main.ts is the main typescript file which is used to bootstrap the angular module.
The check for environment is also performed here .


import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.log(err));

>> in the above code AppModule is being imported from app.module.ts file which is located in app folder

App folder contains the following files

It contains Modules, Components,Components.css, Component template and Services as shown in above image.

1. app.module.ts

>> In this file we imports the angular module( BrowserModule,NgModule) and components (AppComponent)

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';


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


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

2. app.components.ts

>> This file simply defines an angular component and this is where we have defined our app-root selector

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
}

3. app.component.html
>> This is the template file for our app component and this represents the visual part of our component which is rendered in the browser.

<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
  <h1>
    Welcome to {{ title }}!
  </h1>
  <img width="300" alt="Angular Logo" src="Logo.png">
</div>
<h2>Here are some links to help you start: </h2>
<ul>
  <li>
    <h2><a target="_blank" rel="noopener" href="https://angular.io/tutorial">Tour of Heroes</a></h2>
  </li>
  <li>
    <h2><a target="_blank" rel="noopener" href="https://github.com/angular/angular-cli/wiki">CLI Documentation</a></h2>
  </li>
  <li>
    <h2><a target="_blank" rel="noopener" href="https://blog.angular.io/">Angular blog</a></h2>
  </li>
</ul>

4. app.component.css

>> This is the file for applying css in entire angular application.