I am here to continue the discussion around AngularJS 2.0. So far, we have discussed data binding, input properties, output properties, pipes, viewchild, and also directives in Angular 2.0. Now, in this article, I will discuss how to create a custom component like dynamic Grid using all the features which we discuss till now. Also, in case you did not have a look at the previous articles of this series, go through the links mentioned below.
In this Angular 2 article series, we have already discussed basic components and directives concepts in Angular2. Now in this article, I will show you how to create custom components, such as records that display dynamic Grids for using the concept of directives, pipes, and other features of Angular 2.
Now, for creating the dynamic Grid, we first need to create a custom component which will represent the dynamic Grid components. For this purpose, we first add the TypeScript file named app.component.dynamicgrid.ts file and add the below code.
- import { Component, OnInit, Input, Output } from '@angular/core';
-
- @Component({
- moduleId: module.id,
- selector: 'dynamic-grid',
- templateUrl: 'app.component.dynamicgrid.html'
- })
-
- export class DynamicGridComponent implements OnInit {
-
- private _source: Array<any> = new Array<any>();
-
- @Input() private columns: Array<columnDef> = new Array<columnDef>();
-
- constructor() { }
-
- ngOnInit(): void {
- if (this.columns == null || this.columns == undefined) {
- alert("Column Definition of grid not provided.");
- return;
- }
- }
-
- public bindData(data: Array<any>): void {
- if (data != null && data != undefined) {
- this._source = data;
- }
- }
-
- public clearGrid(): void {
- this._source = [];
- }
- }
-
- export class columnDef {
- caption: string;
- dataField: string;
- dataType: columnDataType;
- width: string;
- display: boolean = true;
- }
-
- export enum columnDataType {
- Text,
- Number,
- Datetime,
- Integer,
- }
In the above component, we created one Input Property, named columns, which is basically used for defining the column details such as caption and data field of the Grid columns. Also, we created two public methods within the Grid component called bindData() and clearGrid(). First function is used for binding data into the Grid component. This function takes an array type argument as data. The second method is used for clearing the Grid content.
In the above TypeScript file, we also defined two another classes named columnDef and columnDataType. These two classes are basically enum type classes which can be used for defining the column structure of the dynamic Grid component from the parent component.
Now, add an HTML file for dynamic Grid component templates named app.component.dynamicgrid.html and add the below code.
- <div class="ibox-content">
- <div class="ibox-table">
- <div class="table-responsive">
- <table class="responsive-table table-striped table-bordered table-hover">
- <thead>
- <tr>
- <th *ngFor="let header of columns;let ind=index" [ngStyle]="{'width': header.width}">
- <span>
- {{header.caption}}
- </span>
- </th>
- </tr>
- </thead>
- <tbody>
- <tr *ngFor="let s of _source; let i=index">
- <td *ngFor="let cols of columns; let ind1=index" [ngSwitch]="cols.dataType" [ngStyle]="{'width': cols.width}">
- <span *ngSwitchCase="0">
- {{s[cols.dataField]}}
- </span>
- <span *ngSwitchCase="1">
- {{s[cols.dataField]}}
- </span>
- <span *ngSwitchCase="2">
- {{s[cols.dataField] | date:"fullDate"}}
- </span>
- <span *ngSwitchCase="3">
- {{s[cols.dataField]}}
- </span>
- </td>
- </tr>
- </tbody>
- </table>
- </div>
- </div>
- </div>
In the above code, we used ngFor and ngSwitch for populating the dynamic table columns. Also, we used date pipes for date field value formatting.
Now, we need to create another component within which we use these dynamic Grid components. Actually, this contains an entry form and also the dynamic Grid component. For this purpose, we first create an HTML file named app.component.gridsetting.html and add the below code.
- <div>
- <fieldset>
- <legend>
- Employee Information
- </legend>
- <table style="width:100%;">
- <tr>
- <th>Employee Name</th>
- <td><input type="text" maxlength="100" [(ngModel)]="_modelData.employeeName" /></td>
- </tr>
- <tr>
- <th>Department</th>
- <td><input type="text" maxlength="100" [(ngModel)]="_modelData.department"/></td>
- </tr>
- <tr>
- <th>Designation</th>
- <td><input type="text" maxlength="100" [(ngModel)]="_modelData.designation" /></td>
- </tr>
- <tr>
- <th>Date of Join</th>
- <td><input type="date" [(ngModel)]="_modelData.doj"/></td>
- </tr>
- <tr>
- <th>Salary</th>
- <td><input type="number" [(ngModel)]="_modelData.salary"/></td>
- </tr>
- <tr>
- <td style="text-align:right;"></td>
- <td>
- <input type="button" value="Add" (click)="addData();" />
-
- <input type="button" value="Clear" (click)="clearData()" />
-
- <input type="button" value="Reset Grid" (click)="resetGrid()" />
- </td>
- </tr>
- </table>
- </fieldset>
- </div>
- <div>
- <h2>Employee Details</h2>
- <dynamic-grid [columns]="_columnDetails" #grid></dynamic-grid>
- </div>
Now, add a TypeScript file named app.component.gridsetting.ts and add the below code.
- import { Component, OnInit, ViewChild } from '@angular/core';
- import { DynamicGridComponent, columnDef, columnDataType } from './app.component.dynamicgrid';
-
- @Component({
- moduleId: module.id,
- selector: 'grid-setting',
- templateUrl: 'app.component.gridsetting.html'
- })
-
- export class GridSettingComponent implements OnInit {
- private _columnDetails: Array<columnDef>;
- private _modelData: any = {};
- private _gridData: Array<any> = new Array<any>();
- private _srlNo: number;
-
- @ViewChild('grid') private _gridComponent: DynamicGridComponent;
-
- constructor() {
- this._columnDetails = [
- { caption: 'Srl No', dataField: 'srlNo', dataType: columnDataType.Integer, width: '10%', display: true },
- { caption: 'Employee Name', dataField: 'employeeName', dataType: columnDataType.Text, width: '30%', display: true },
- { caption: 'Departmentr', dataField: 'department', dataType: columnDataType.Text, width: '15%', display: true },
- { caption: 'Designation', dataField: 'designation', dataType: columnDataType.Text, width: '15%', display: true },
- { caption: 'Date Of Join', dataField: 'doj', dataType: columnDataType.Datetime, width: '15%', display: true },
- { caption: 'Salary', dataField: 'salary', dataType: columnDataType.Number, width: '15%', display: true }];
- }
-
- ngOnInit(): void {
- this._srlNo = 1;
- }
-
- private addData(): void {
- if (this.validateData()) {
- this._modelData.srlNo = this._srlNo;
- this._srlNo += 1;
- this._modelData.doj = new Date(this._modelData.doj);
- this._gridData.push(this._modelData);
- this.clearData();
- this._gridComponent.bindData(this._gridData);
- }
- }
-
- private clearData(): void {
- this._modelData = {};
- }
-
- private validateData(): boolean {
- let status = true;
- if (this.isUndefined(this._modelData.employeeName)) {
- alert('Employee Name never blank');
- status = false;
- }
- else if (this.isUndefined(this._modelData.department)) {
- alert('Department never blank');
- status = false;
- }
- else if (this.isUndefined(this._modelData.designation)) {
- alert('Designation never blank');
- status = false;
- }
- else if (this.isUndefined(this._modelData.salary)) {
- alert('Salary never blank');
- status = false;
- }
- else if (this.isUndefined(this._modelData.doj)) {
- alert('Date of Join never blank');
- status = false;
- }
- return status;
- }
-
- private isUndefined(data: any): boolean {
- return typeof (data) === "undefined";
- }
-
- private resetGrid(): void {
- this._gridData = [];
- this._modelData = {};
- this._gridComponent.clearGrid();
- }
- }
In the above component, for accessing the public method of the Grid component, we use viewchild concept. Now, add another TypeScript file named app.module.ts and write down the below code.
- import { NgModule } from '@angular/core';
- import { BrowserModule } from '@angular/platform-browser';
- import { FormsModule } from "@angular/forms";
- import { GridSettingComponent } from './src/app.component.gridsetting';
- import { DynamicGridComponent } from './src/app.component.dynamicgrid';
-
- @NgModule({
- imports: [BrowserModule, FormsModule],
- declarations: [GridSettingComponent, DynamicGridComponent],
- bootstrap: [GridSettingComponent]
- })
- export class AppModule { }
Now, add another TypeScript file named main.ts and add the below code.
- import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
-
- import { AppModule } from './app.module';
-
- const platform = platformBrowserDynamic();
- platform.bootstrapModule(AppModule);
Now, add another HTML file named index.html and add the below code.
- <!DOCTYPE html>
- <html>
- <head>
- <title>Angular2 - Custom Grid</title>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <link href="../resources/style/style1.css" rel="stylesheet" />
- <!-- 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>
- <script src="../systemjs.config.js"></script>
- <script>
- System.import('app').catch(function (err) { console.error(err); });
- </script>
- </head>
- <body>
- <grid-setting>Loading</grid-setting>
-
- </body>
- </html>
Now, run the code. The output is shown below.