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.
- AngularJS 2.0 From Beginning Introduction of AngularJS 2.0 (Day 1)
- AngularJS 2.0 From Beginning Component (Day 2)
- AngularJS 2.0 From Beginning Data Binding (Day 3)
- AngularJS 2.0 From Beginning Input Data Binding (Day 4)
- AngularJs 2.0 From Beginning - Output Property Binding (Day 5)
- AngularJs 2.0 From Beginning - Attribute Directive (Day 6)
- AngularJs 2.0 From Beginning - Structural Directives (Day 7)
- AngularJs 2.0 From Beginning - Pipes (Day 8)
- AngularJs 2.0 From Beginning - Viewchild (Day 9)
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,
- }
- <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>
- <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>
- 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();
- }
- }
- 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 { }
- import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
- import { AppModule } from './app.module';
- const platform = platformBrowserDynamic();
- platform.bootstrapModule(AppModule);
- <!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>


sanjay rorPosted Aug 29, 2018, 4:55 AM
This is not dynamic at all, This is static grid..
SUbodh CHudharyPosted Feb 10, 2018, 3:28 PM
Hi, very nice article. How could we make this fields as Editable textboxes so that user can update values. Kindly guide
Kunal GuptaPosted Aug 23, 2017, 2:11 PM
Using ur article ,I am able to bind grid but i want to bind grid dynamically with sql server database table.Please help me as soon as possible....
Ravi KandelPosted Mar 8, 2017, 8:40 AM
Awesome Thanks for sharing