import { Component } from '@angular/core';
import {TableInfo} from './CmpTable';

interface People {
  name : string;
  address : string;
  age : number;
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html'
})
export class AppComponent {
  name = 'Angular'; 
  data1 : People[] = [{name: 'John', address: 'London', age: 45},
    {name: 'Thole', address: 'Dieng', age: 13}];
  data2 : People[] = [{name: 'Jingglang', address: 'Ndeso', age: 25},
    {name: 'Marutul', address: 'Eks Depag', age: 39}];
  data: People[];
  
tableInfo: TableInfo;
	constructor() {
		this.tableInfo = new TableInfo;
		this.tableInfo.key = 'table1';
		this.tableInfo.onSave = () => {
			this.saveDefaultParameter(this.tableInfo.key, JSON.stringify(this.tableInfo.columnsInfo));
		};
		let saved = this.getDefaultParameter(this.tableInfo.key);
		let columnsInfo = JSON.parse(saved);
		this.tableInfo.columnsInfo = columnsInfo;
		this.data = this.data1;
	}
  
  saveDefaultParameter(paramName: string, value: string) {
		localStorage.setItem(paramName, value);
	}

	getDefaultParameter(paramName: string): string {
		return localStorage.getItem(paramName);
	}
	
	next() {
	  this.data = this.data == this.data1 ? this.data2 : this.data1;
	  this.tableInfo.relayoutBody();
	}
  
}


/*
Copyright 2017 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/
import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent }  from './app.component';
import { CmpTable } from './CmpTable';

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


/*
Copyright 2017 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

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

platformBrowserDynamic().bootstrapModule(AppModule);


/*
Copyright 2017 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/
<!DOCTYPE html>
<html>
  <head>
    <title>Angular Quickstart</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="styles.css">
    <!-- Polyfills -->
    <script src="https://unpkg.com/core-js/client/shim.min.js"></script>

    <script src="https://unpkg.com/zone.js@0.8.4?main=browser"></script>
    <script src="https://unpkg.com/systemjs@0.19.39/dist/system.src.js"></script>
    <script src="systemjs.config.js"></script>
    <script>
      System.import('main.js').catch(function(err){ console.error(err); });
    </script>
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
     <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
  </head>

  <body>
    <my-app>Loading AppComponent content here ...</my-app>
  </body>

</html>


<!-- 
Copyright 2017 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
-->
/**
 * WEB ANGULAR VERSION
 * (based on systemjs.config.js in angular.io)
 * System configuration for Angular samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
  System.config({
    // DEMO ONLY! REAL CODE SHOULD NOT TRANSPILE IN THE BROWSER
    transpiler: 'ts',
    typescriptOptions: {
      // Copy of compiler options in standard tsconfig.json
      "target": "es5",
      "module": "commonjs",
      "moduleResolution": "node",
      "sourceMap": true,
      "emitDecoratorMetadata": true,
      "experimentalDecorators": true,
      "lib": ["es2015", "dom"],
      "noImplicitAny": true,
      "suppressImplicitAnyIndexErrors": true
    },
    meta: {
      'typescript': {
        "exports": "ts"
      }
    },
    paths: {
      // paths serve as alias
      'npm:': 'https://unpkg.com/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      'app': 'app',

      // angular bundles
      '@angular/animations': 'npm:@angular/animations/bundles/animations.umd.js',
      '@angular/animations/browser': 'npm:@angular/animations/bundles/animations-browser.umd.js',
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser/animations': 'npm:@angular/platform-browser/bundles/platform-browser-animations.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/router/upgrade': 'npm:@angular/router/bundles/router-upgrade.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
      '@angular/upgrade': 'npm:@angular/upgrade/bundles/upgrade.umd.js',
      '@angular/upgrade/static': 'npm:@angular/upgrade/bundles/upgrade-static.umd.js',

      // other libraries
      'rxjs':                      'npm:rxjs@5.0.1',
      'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js',
      'ts':                        'npm:plugin-typescript@5.2.7/lib/plugin.js',
      'typescript':                'npm:typescript@2.2.1/lib/typescript.js',

    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        main: './main.ts',
        defaultExtension: 'ts',
        meta: {
          './*.ts': {
            loader: 'systemjs-angular-loader.js'
          }
        }
      },
      rxjs: {
        defaultExtension: 'js'
      }
    }
  });

})(this);

/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/
var templateUrlRegex = /templateUrl\s*:(\s*['"`](.*?)['"`]\s*)/gm;
var stylesRegex = /styleUrls *:(\s*\[[^\]]*?\])/g;
var stringRegex = /(['`"])((?:[^\\]\\\1|.)*?)\1/g;

module.exports.translate = function(load){
  if (load.source.indexOf('moduleId') != -1) return load;

  var url = document.createElement('a');
  url.href = load.address;

  var basePathParts = url.pathname.split('/');

  basePathParts.pop();
  var basePath = basePathParts.join('/');

  var baseHref = document.createElement('a');
  baseHref.href = this.baseURL;
  baseHref = baseHref.pathname;

  if (!baseHref.startsWith('/base/')) { // it is not karma
    basePath = basePath.replace(baseHref, '');
  }

  load.source = load.source
    .replace(templateUrlRegex, function(match, quote, url){
      let resolvedUrl = url;

      if (url.startsWith('.')) {
        resolvedUrl = basePath + url.substr(1);
      }

      return 'templateUrl: "' + resolvedUrl + '"';
    })
    .replace(stylesRegex, function(match, relativeUrls) {
      var urls = [];

      while ((match = stringRegex.exec(relativeUrls)) !== null) {
        if (match[2].startsWith('.')) {
          urls.push('"' + basePath + match[2].substr(1) + '"');
        } else {
          urls.push('"' + match[2] + '"');
        }
      }

      return "styleUrls: [" + urls.join(', ') + "]";
    });

  return load;
};
import {Component, Input, AfterViewInit, ViewChild, ElementRef} from '@angular/core';


export class ColumnInfo {
	visible: boolean = true;
	order: number;
	name?: string;
	sorting?: string;
}

export class TableInfo {
	key: string;
	columnsInfo: ColumnInfo[];
	onSave: any;
	relayoutBody = () => {};
}

declare var jQuery: any;

@Component({
	moduleId: module.id,
	selector: 'p-table',
	templateUrl: 'CmpTable.html',
	styleUrls: ['CmpTable.css'],
})

export class CmpTable implements AfterViewInit {
	table: HTMLTableElement;
	lstColumns: any[];
	@ViewChild('dropdown') dropdown: any;
	columnsInfo: ColumnInfo[];
	@Input() tableInfo: TableInfo;
	preventDropdownClose = false;
	constructor(private elRef: ElementRef) {
	}

	ngAfterViewInit() {
		this.table = this.elRef.nativeElement.getElementsByTagName('table')[0];

		setTimeout(() => {
			this.tableInfo.relayoutBody = () => {
				jQuery(this.table).css('visibility','hidden');
				setTimeout(() => this.relayoutBody());
			};
			if (this.tableInfo.columnsInfo == null) {
				this.tableInfo.columnsInfo = [];
			}
			this.columnsInfo = this.tableInfo.columnsInfo;
			let lstHeaderCell = this.table.children.item(0).children[0].children;
			for (let i = 0; i < lstHeaderCell.length; i++) {
				let aColumn = <any> lstHeaderCell.item(i);
				if (i >= this.columnsInfo.length) {
					this.columnsInfo.push({visible: true, order: i});
				}
				this.columnsInfo[i].name = aColumn.innerText;
				aColumn.dataset.order = i;
			}

			let tbody = this.table.children.item(1).children;
			for (let i = 0; i < tbody.length; i++) {
				let tr = tbody[i];
				for (let j = 0; j < tr.children.length; j++) {
					(<any> tr.children[j]).dataset.order = j;
				}
			}
			this.defineMenuDatasource();

			this.initDisplay();
		});

		jQuery(this.dropdown.nativeElement).on('hide.bs.dropdown', (e) => {
			if (this.preventDropdownClose) {
				e.preventDefault();
			} else {
				this.tableInfo.onSave();
			}
			this.preventDropdownClose = false;
		});
	}

	toggle(rowNum: number) {
		for (let i = 0; i < this.columnsInfo.length; i++) {
			let anInfo = this.columnsInfo[i];
			if (anInfo.order == rowNum) {
				anInfo.visible = !anInfo.visible;
			}
		}
		this.refreshVisibility();
	}

	up(rowNum: number) {
		this.preventDropdownClose = true;
		this.orderColumn(true, rowNum);
		let selectedColumn: ColumnInfo;
		for (let i = 0; i < this.columnsInfo.length; i++) {
			let anInfo = this.columnsInfo[i];
			if (anInfo.order === rowNum) {
				selectedColumn = anInfo;
				break;
			}
		}

		let pivot: ColumnInfo;
		for (let i = 0; i < this.columnsInfo.length; i++) {
			let anInfo = this.columnsInfo[i];
			if (anInfo.order === (rowNum - 1)) {
				pivot = anInfo;
				break;
			}
		}

		pivot.order = rowNum;
		selectedColumn.order = rowNum - 1;
		this.defineMenuDatasource();
	}

	private defineMenuDatasource() {
		this.lstColumns = Array(this.columnsInfo.length);
		for (let i = 0; i < this.columnsInfo.length; i++) {
			let anInfo = this.columnsInfo[i];
			this.lstColumns[anInfo.order] = {text: anInfo.name, visible: anInfo.visible};
		}
	}

	dontClose() {
		this.preventDropdownClose = true;
	}
	down(rowNum: number) {
		this.preventDropdownClose = true;
		this.orderColumn(false, rowNum);
		let selectedColumn: ColumnInfo;
		for (let i = 0; i < this.columnsInfo.length; i++) {
			let anInfo = this.columnsInfo[i];
			if (anInfo.order === rowNum) {
				selectedColumn = anInfo;
				break;
			}
		}

		let pivot: ColumnInfo;
		for (let i = 0; i < this.columnsInfo.length; i++) {
			let anInfo = this.columnsInfo[i];
			if (anInfo.order === (rowNum + 1)) {
				pivot = anInfo;
				break;
			}
		}

		pivot.order = rowNum;
		selectedColumn.order = rowNum + 1;
		this.defineMenuDatasource();
	}

	orderColumn(up: boolean, rowNum: number) {
		let index = 0;
		for (let i = 0; i < this.columnsInfo.length; i++) {
			if (this.columnsInfo[i].order == rowNum) {
				index = i;
				break;
			}
		}

		jQuery(this.table).find('[data-order="' + index + '"]').each((index, value) => {
			if (up) {
				jQuery(value).prev().before(value);
			} else {
				jQuery(value).next().after(value);
			}
		});

	}

	private initDisplay() {
		this.refreshVisibility();
		for (let i = 0; i < this.columnsInfo.length; i++) {
			let anInfo = this.columnsInfo[i];
			jQuery(this.table).find('[data-order="' + i + '"]').each((index, value) => {
				if (anInfo.order > i) {
					jQuery(value).parent().children().eq(anInfo.order).after(value);
				} else if (anInfo.order < i) {
					jQuery(value).parent().children().eq(anInfo.order).before(value);
				}
			});
		}
	}

	relayoutBody() {
		let tbody = this.table.children.item(1).children;
		for (let i = 0; i < tbody.length; i++) {
			let tr = tbody[i];
			for (let j = 0; j < tr.children.length; j++) {
				(<any> tr.children[j]).dataset.order = j;
			}
		}
		this.refreshVisibility();
		for (let i = 0; i < this.columnsInfo.length; i++) {
			let anInfo = this.columnsInfo[i];
			jQuery(tbody).find('[data-order="' + i + '"]').each((index, value) => {
				if (anInfo.order > i) {
					jQuery(value).parent().children().eq(anInfo.order).after(value);
				} else if (anInfo.order < i) {
					jQuery(value).parent().children().eq(anInfo.order).before(value);
				}
			});
		}
		jQuery(this.table).css('visibility','visible');
	}

	refreshVisibility() {

		for (let i = 0; i < this.columnsInfo.length; i++) {
			let anInfo = this.columnsInfo[i];
			jQuery(this.table).find('[data-order="' + i + '"]').each((index, value) => {
				if (anInfo.visible) {
					jQuery(value).show();
				} else {
					jQuery(value).hide();
				}
			});
		}

	}

	reset() {
		this.preventDropdownClose = true;
		for (let i = 0; i < this.columnsInfo.length; i++) {
			let anInfo = this.columnsInfo[i];
			jQuery(this.table).find('[data-order="' + i + '"]').each((index, value) => {
				if (anInfo.order > i) {
					jQuery(value).parent().children().eq(i).before(value);
				} else if (anInfo.order < i) {
					jQuery(value).parent().children().eq(i).after(value);
				}
			});
			anInfo.order = i;
			anInfo.visible = true;
		}
		this.defineMenuDatasource();
		this.refreshVisibility();
	}

}
<div #dropdown class="dropdown">
	<button type="button" class="btn dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
		<span class="caret"></span>
	</button>
	<ul class="dropdown-menu">
		<li class="dropdown-header">Visible Columns</li>
		<li *ngFor="let clm of lstColumns; let rowNum=index">
			<div  (click)="dontClose()">
				<label><input type="checkbox" (click)="toggle(rowNum)" [checked]="clm.visible"> {{clm.text}}</label>
				<div class="pull-right">
					<a *ngIf="rowNum > 0" (click)="up(rowNum)"><i class="glyphicon glyphicon-chevron-up"></i></a>
					<a *ngIf="rowNum < (lstColumns.length - 1)" (click)="down(rowNum)"><i class="glyphicon glyphicon-chevron-down"></i></a>
				</div>
			</div>
		</li>
		<li role="separator" class="divider"></li>
		<li><a class="btn btn-default" (click)="reset()">Reset</a></li>
	</ul>
</div>
<ng-content></ng-content>
<h2>Table Column Order and Visibility</h2>

<p>
  By adding p-table tag, the table has feature to reorder the columns and toggle its visibility
</p>

<p-table [tableInfo]="tableInfo">
	<table class="table table-stripped table-bordered ">
		<thead>
			<tr>
				<th>Name</th>
				<th>Address</th>
				<th>Age</th>
			</tr>
		</thead>
		<tbody>
		  <tr *ngFor="let indv of data">
		    <td>{{indv.name}}</td>
		    <td>{{indv.address}}</td>
		    <td>{{indv.age}}</td>
		  </tr>
		</tbody>
	</table>
</p-table>

<a (click)="next()">Next</a>
:host .dropdown {
	position: absolute;
	padding-left: 0;
}

input {
	margin: 0;
}

label {
	font-weight: normal;
	margin: 0;
	min-width: 80%;
}
.dropdown .btn {
	padding: 0 2px;
	margin-top: -10px;
	background-color: transparent;
}

:host /deep/ .table > thead > tr > th {
	text-align: center;
}

:host /deep/ ul > li > div{
	padding: 2px;
	font-size: 10px;
}

:host /deep/ ul > li > div:hover {
	background-color: whitesmoke;
}
body {
  margin: 1em;
}