Introduction
In the previous part of the tutorial series Learning Angular 2 Step by step, we have done setup angular 2 development environment & created a very simple "Hello world" application in angular 2.Today in this tutorial, we will continue learning Angular 2 step by step and here we will learn all about Angular 2 component.
In Angular 2 “everything is a component.” That's why Angular 2 is also called a component-based framework, which allows us to create reusable UI widgets.
Before reading this article, I would recommend reading my previous tutorial where I have explained how to setup angular 2 development environment & create a simple "Hello World" application for better understanding.
Create a new Angular 2 component
We know that angular 2 is written in TypeScript. So, we have to create a typescript class first. And then we can mark this class as an Angular 2 component with the help of a Component decorator.Let's create the EmployeeList Component.
Here in our application, we will add a folder named EmployeeList first inside the src > App folder and then add a typescript file employee-list.component.ts for creating the EmployeeList component.
Right click on the folder App inside the src folder > New Folder > enter folder name EmployeeList and then right click on the EmployeeList folder > New File > enter file name employee-list.component.ts
Till now it's nothing but a TypeScript class. But we can mark this class as an Angular 2 component with the help of a Component decorator.
export class EmployeeListComponent { }
Till now it's nothing but a TypeScript class. But we can mark this class as an Angular 2 component with the help of a Component decorator. The Component decorator allows us to add meta-data that will tell Angular 2 how to process a class. Let's convert the TypeScript Class to Angular 2 Component.
First of all, we have to import the Component from '@angular/core' and then we will apply the @Component decorator in the TypeScript class.
import {Component} from '@angular/core' @Component({ selector:'employee-list', templateUrl:'employee-list.component.html', moduleId: module.id }) export class EmployeeListComponent { }
You can see here I have added selector, templateUrl, and moduleId meta-data. There are more Metadata Properties we can define in the component decorator we will see later. You can read from here.
selector - defines the name of the HTML tag where this component will live.
templateUrl - In templateUrl we can define URL to an external file containing a template for the view.
moduleId - moduleId is used to resolve relative paths for templates. module.id works when using CommonJS. You can see here in tsconfig.json file we have used "commonjs" as module.
You can notice here in the templateUrl, I have added employee-list.component.html but we will not add the template file in the root path of the application. We will create the template file in the EmployeeList folder. So how the relative path will be resolved. It will be resolved by the moduleId meta-data.
Now, this is an angular 2 component. In this EmployeeList component, we will show a list of employees in this component.
And for this, we need to have a model for employee information first.
Create a model class (EmployeeModel)
Here in our application, we will create a folder named "Models" then we will create the model inside the folder.Right click on the App folder inside the src folder > New Folder > enter folder name Models and then Right-click on the Models folder > New File > enter file name EmployeeModel.ts
export class EmployeeModel{ public EmployeeID:number; public FirstName:string; public LastName:string; public ContactNo:string; public Designation:string; }
Update EmployeeList component for showing list of employees in this component.
import {Component, OnInit} from '@angular/core' import {EmployeeModel} from '../Models/EmployeeModel' @Component({ selector:'employee-list', templateUrl:'employee-list.component.html', moduleId: module.id }) export class EmployeeListComponent implements OnInit{ public EmployeeList: Array<EmployeeModel> = []; public LoadIntialData():void{ this.EmployeeList = [{ EmployeeID:1, FirstName: "Sourav", LastName:"Mondal", ContactNo: "1234567890", Designation:"Software Developer" }, { EmployeeID:2, FirstName: "Rik", LastName:"Decosta", ContactNo: "1478523690", Designation:"Software Developer" },{ EmployeeID:3, FirstName: "Jhon", LastName:"Decosta", ContactNo: "5874213690", Designation:"Software Developer" }]; } ngOnInit(){ this.LoadIntialData(); } }
See in the line no 2, we have imported the EmployeeModel and in line 9, I have added a property EmployeeList of type Array
And also added a method LoadIntialData in the EmployeeList component for loading employee data. For now, I have added some static data here later we will learn how to use Http client for fetching dynamic data from remote server.
Now we will call the function for load initial data. We can do that in the constructor function. But we will not because writing complex logic in the constructor function is not recommended. ngOnInit() is a good place for a component to fetch its initial data.
Now the question is what is ngOnInit & how to use it?
Directive and component instances have a lifecycle as Angular creates, updates, and destroys them. ngOnInit is a lifecycle hook that calls after creating the component. Let's see how we can use this ngOnInit lifecycle hook.
You can see here in line 1 in the above EmployeeList Component, we have imported OnInit interface. This is a component lifecycle hook called just after loading the component. This is the best place to call the LoadIntialData for loading the initial data. So you can notice on line 8 of the EmployeeList component I have implemented OnInit interface and called the ngOnInit method in line 33 from where we have called the LoadIntialData method.
Till now we have not created the template employee-list.component.html
Create the employee-list.component.html
We have defined the employee-list.component.html in the templateUrl meta-data in the EmployeeList Component. So we have to create the template.I will create the template inside the EmployeeList folder that we have created in the App folder.
Right-click on the EmployeeList folder > New File > enter name employee-list.component.html and then add the following HTML code for showing the employee list.
employee-list.component.html
<h2>Employee List</h2> <table class="table table-responsive table-bordered table-striped"> <thead> <tr> <th>Employee ID</th> <th>Employee Name</th> <th>Contact No</th> <th>Designation</th> </tr> </thead> <tbody> <tr *ngFor="let item of EmployeeList"> <td>{{item.EmployeeID}}</td> <td>{{item.FirstName}} {{item.LastName}}</td> <td>{{item.ContactNo}}</td> <td>{{item.Designation}}</td> </tr> </tbody> </table>
Update app.module.ts file
Our EmployeeList component is completed. Now we have to add the component in our bootstrap Module in the app.module.ts file. Let me add this EmployeeList component in bootstrap so we can see in the index page.import { NgModule } from "@angular/core"; import {BrowserModule} from "@angular/platform-browser"; import {AppComponent} from "./app.component" import {EmployeeListComponent} from './EmployeeList/employee-list.component' @NgModule({ imports: [BrowserModule], declarations: [AppComponent,EmployeeListComponent], // bootstrap:[AppComponent], bootstrap:[EmployeeListComponent] }) export class AppModule{ }
Update index.html page
<!DOCTYPE html> <html> <head> <title>This is my frist angular 2 app</title> <meta charset="utf-8"/> <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <!-- 1. Load libraries --> <!-- Polyfill(s) for older browsers --> <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/reflect-metadata/Reflect.js"></script> <script src="../node_modules/systemjs/dist/system.src.js"></script> <!-- System.JS configuration --> <script src="./Systemjs.config.js"></script> <script> System.config({ "defaultJSExtensions": true }) System.import('app').catch(function(err){ console.log(err); }) </script> </head> <body class="container"> <!--<app>Please Wait...</app>--> <div class="row"> <div class="md-col-12"> <employee-list>Loading Employee List...</employee-list> </div> </div> </body> </html>I have updated the index.html page for showing employee list component in this page. Also, I have added bootstrap CSS for make it looks better.