This is Part 3 of "CRUD Operations in Asp MVC using Angular 2 with Basics."
Before starting, I will recommend you read my previous articles about Angular and its features and versions.
In our previous articles, we have added the following Angular files and controller. Please find the below image for your reference:
Now, let's add employee folder under "src/app" folder.
Next, add an Employee Component under Employee Folder.
To create
Select Employee Folder -> Right Click -> Add -> Select "TypeScript File" -> Enter the name of our typescript file "Employee.Component.ts" -> Click ok
Now you can see, an empty employee component has been added in our employee folder. Please copy the below code and paste it in our employee component.
- import { Component } from '@angular/core'; // importing component from @angular/core directives
-
- @Component({
- selector: 'emp', //This is the selector of our section
- template: '<h1>This is our Employee Component', //HTML tag to render inside of emp selector
- })
-
- export class EmployeeComponent{
- //you can declare class properties here
- }
Then next, we have to register our employee component into our root module.
Note
Our root module is app.module.ts
Note
We have declared our Employee component also a root component for App Module.
- import { NgModule } from '@angular/core';
- import { BrowserModule } from '@angular/platform-browser';
- import { AppComponent } from './app.component';
- import {EmployeeComponent } from './Employee/EmployeeComponent';
-
- @NgModule({
- imports: [ BrowserModule ],
- declarations: [AppComponent, EmployeeComponent ],
- bootstrap: [ AppComponent,EmployeeComponent ] //declared employee component also as a root component
- })
- export class AppModule { }
Let's add our emp selector into our index page and run it.
- <!DOCTYPE html>
- <html>
- <head>
- <title>Angular QuickStart</title>
- <base href="/src/">
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <link rel="stylesheet" href="styles.css">
-
-
- <script src="/node_modules/core-js/client/shim.min.js"></script>
-
- <script src="/node_modules/zone.js/dist/zone.js"></script>
- <script src="/node_modules/systemjs/dist/system.src.js"></script>
-
- <script src="systemjs.config.js"></script>
- <script>
- System.import('main.js').catch(function(err){ console.error(err); });
- </script>
- </head>
-
- <body>
- <my-app>Loading AppComponent content here ...</my-app>
- <emp></emp>
- </body>
- </html>
The result has been displayed as we expected.
Here, instead of writing HTML inside employee component, let's refer to an external HTML file. To do this, first, add an HTML file inside employee folder.
Modify the below code in your employee component.
- import { Component } from '@angular/core';
-
- @Component({
- selector: 'emp',
- templateUrl: 'app/Employee/Employee.Component.html', //Refering the external html file
- })
-
- export class EmployeeComponent{
-
- }
templateurl property is used to refer to the external HTML file.
Now, let's add some properties in our employee component and display the values in our HTML page.
- import { Component } from '@angular/core';
-
- @Component({
- selector: 'emp',
- templateUrl: 'app/Employee/Employee.Component.html',
- })
-
- export class EmployeeComponent{
- EmpId: number = 1;
- EmpName: string = "Ramesh";
- EmpAge: number = 26;
- EmpCity: string = "Bangalore";
- EmpMobileNo: string = "1234567890";
- }
Add the below HTML script into our
Employee.Component.Html file
- <h1> This is our employee component</h1>
- <table border="1">
- <thead>
- <tr>
- <td>Name</td>
- <td>Age</td>
- <td>City</td>
- <td>Mobile No</td>
- </tr>
- </thead>
- <tbody>
- <tr>
- <td>{{EmpName}}</td>
- <td>{{EmpAge}}</td>
- <td>{{EmpCity}}</td>
- <td>{{EmpMobileNo}}</td>
- </tr>
- </tbody>
- </table>
Run our project and we will see the result.
The result has been displayed as we expected. Now, let's add multiple rows in a table using *NgFor and "any" datatype.
Browser Module provides the *ngFor and *ngIf directives. To know more about *ngFor and *ngIf please click
Here
*ngFor directive is used to loop the elements.
*ngIf directive is used to evaluate the conditions.
This directives are called structural directives.
First let's add a simple interface to our employee folder. To add, select Employee folder -> Right Click -> select "Type Script File" -> enter the name of the file "IEmployee.ts" then click OK . Please, find the below image for your reference:
Copy the below code and paste it in our IEmployee interface.
- export interface IEmployee {
- EmpId: number;
- EmpName: string;
- EmpAge: number;
- EmpCity: string;
- EmpMobileNo: string;
- }
Note
Export keyword used to export the interfaces or classes in any other compoenents and services. If we didn't mention the export keyword in our interface or class, we cannot reuse this on any other components.
Let's import our IEmployee interface into our Employee Component. Please find the below code for your reference.
- import { Component } from '@angular/core';
- import { IEmployee } from './IEmployee';
-
- @Component({
- selector: 'emp',
- templateUrl: 'app/Employee/Employee.Component.html',
- })
-
- export class EmployeeComponent {
- EmployeeDetails: IEmployee[];
- constructor() {
- this.EmployeeDetails = [
- { EmpId: 1, EmpName: 'Ramesh', EmpAge: 26, EmpCity: 'Bangalore', EmpMobileNo: '1234567890' },
- { EmpId: 2, EmpName: 'Kiran', EmpAge: 22, EmpCity: 'Chennai', EmpMobileNo: '1234567890' },
- { EmpId: 3, EmpName: 'Anisha', EmpAge: 29, EmpCity: 'Delhi', EmpMobileNo: '1234567890' }
- ]
- }
- }
Let's make the chages in our HTML file and we will see the result.
- <h1> This is our employee component</h1>
- <table border="1">
- <thead>
- <tr>
- <td>Name</td>
- <td>Age</td>
- <td>City</td>
- <td>Mobile No</td>
- </tr>
- </thead>
- <tbody >
- <tr *ngFor="let employee of EmployeeDetails">
- <td>{{employee.EmpName}}</td>
- <td>{{employee.EmpAge}}</td>
- <td>{{employee.EmpCity}}</td>
- <td>{{employee.EmpMobileNo}}</td>
- </tr>
- </tbody>
- </table>
You can see here, the result has been displayed as we expected. Next let's get the data from database using HTTP module and Services.
To create service, please follow the below steps.
Select Employee Folder => Right Click => Add => Select "Type Script File" => Click OK => Enter the service name "Employee.service.ts" => Click Ok. Please find the sample image for your reference.
Once the service has been created, copy the below code and paste it into our IEmployee.service.ts
- import { Injectable} from '@angular/core'
-
- @Injectable()
- export class EmployeeService {
-
- }
Let's understand the code,
@Injectable is used for dependency injection. Dependency Injection (DI) is a way to create objects that depend upon other objects.
In Angular, if you are creating a service, I recommended adding @Injectable for future purpose. For now, we don't have any dependencies.
Note
We are importing "@Injectable" from @angular/core directives.
Let's import our IEmployee interface and Http module in our Employee service. Please find the sample code below:
- import { Injectable } from '@angular/core'
- import {IEmployee } from './IEmployee';
- import {Http,Response } from '@angular/http';
-
- @Injectable()
- export class EmployeeService {
- constructor(private _http: Http) {
-
- }
- }
Here, you can see, we have implemented the constructor for our employee service and injected the HTTP module. Here @Injectable is required to inject our HTTP Module. If you are not using @Injectable, you will get the run time exception. Please find the sample image below,
What is Http Module?
HTTP is a protocol which is used to communicate with the remote server. In Angular, the same HTTP module is going to be used for communicating with the server (Controller).
To know more about HTTP Module, please refer to the below links,
Let's add a method to communicate with the controller to get the list of records from the database.
Note
We have already implemented the controller and database in our part two tutorial:
We have created a method "getEmployeeDetails()" to get the list of employees from the database. Used _http.get method to communicate with our GetAllEmployees action result in our Employee Controller.
In the above image, we can see the error message. We cannot assign the Obesevable<Response> to IEmployee[] property.
The _http.get method will return an observable response. So, we have to assign our resposne to Observable<IEmployee[]>, so let's add few changes in our code:
Now, we have assigned our response to Observable<IEmployee[]>. Note: Observable is importing from rxjs/Observable.
But now, we are facing another issue -- it's saying we cannot assign Observable<Response> to Observable<IEmployee[]>
To convert our Response to IEmployee[], we have an one more property called map which needs to be imported from "rxjs/add/operator/map". Let's convert Response to IEmployee[] using map. Please find the below code for your reference:
- import { Injectable } from '@angular/core'
- import {IEmployee } from './IEmployee';
- import { Http, Response } from '@angular/http';
- import { Observable } from 'rxjs/Observable';
- import 'rxjs/add/operator/map';
-
- @Injectable()
- export class EmployeeService {
- constructor(private _http: Http) {
-
- }
-
- getEmployeeDetails(): Observable<IEmployee[]> {
- return this._http.get("http://localhost:57997/Employee/GetAllEmployees").map((response: Response) => <IEmployee[]>response.json());
- }
- }
Our service has been created successfully now. Let's use import our service in our Employee Component.
Before that, let's import an HTTP module in our App.Module.ts. Please refer to the below code for your reference:
- import { NgModule } from '@angular/core';
- import { BrowserModule } from '@angular/platform-browser';
- import { AppComponent } from './app.component';
- import { EmployeeComponent } from './Employee/Employee.Component';
- import { HttpModule } from '@angular/http';
-
- @NgModule({
- imports: [ BrowserModule,HttpModule ],
- declarations: [AppComponent, EmployeeComponent ],
- bootstrap: [ AppComponent ,EmployeeComponent]
- })
- export class AppModule { }
Open our employee component, copy and paste the below code.
- import { Component,OnInit } from '@angular/core';
- import { IEmployee } from './IEmployee';
- import { EmployeeService } from './Employee.service';
- @Component({
- selector: 'emp',
- templateUrl: 'app/Employee/Employee.Component.html',
- providers:[EmployeeService]
- })
-
- export class EmployeeComponent implements OnInit {
- EmployeeDetails: IEmployee[];
- //Insjecting service in our constructor
- constructor(private _EmployeeService: EmployeeService) {
-
- }
- ngOnInit() {
- //calling a method
- this.LoadEmployeeData();
- }
- //Created a method to call getEmployeeDetails method in our Employee Service.
- LoadEmployeeData() {
- this._EmployeeService.getEmployeeDetails().subscribe((employeeData) => this.EmployeeDetails = employeeData);
- //Subscribe method is used to convert our Observable response to IEmployee[] response
- }
- }
Let's understand the code step by step,
First import the service in our Employee.Component.ts. Then import OnInit in @angular/core.
Note
The OnInit method will render after the constructor.
We can declare all the dependency and variable values assigned in the constructor. We can perform our custom functionality in the NgOnInit method.
Use providers property use service in our Component.
Create constructor and inject our EmployeeService. Then create a method "LoadEmployeeDate" to call the service method "getEmployeeDetails"
Note
The subscribe method is used to convert our Observable<IEmployee[]> response to IEmployee[]
In ngOnInit method, let's call the method "LoadEmployeeData()". Save and Run our project.
The result has been displayed as we expected. In our next article, let's perform Add, Update and Delete operations using Angular.
Please give your valuable comments to improve my article writing. Thanks.