<!DOCTYPE html>
<html>
<head>
   <base href="./" />
  <title>Angular Material Plunker</title>

  <!-- Load common libraries -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/typescript/2.1.1/typescript.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/core-js/2.4.1/core.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/zone.js/0.8.5/zone.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.min.js"></script>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    
  <!-- Configure SystemJS -->
  <script src="systemjs.config.js"></script>

  <script>
    System
      .import('app/main.ts')
      .catch(console.error.bind(console));
  </script>

  <!-- Load the Angular Material stylesheet -->
  <link href="https://unpkg.com/@angular/material/prebuilt-themes/indigo-pink.css" rel="stylesheet">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <style>body { font-family: Roboto, Arial, sans-serif; }</style>
</head>

<body>
    <app-root>Loading...</app-root>
<!--input-form-example>Loading Material Docs example...</input-form-example-->
</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 -->
angular.module('myApp', ['smart-table','lrDragNDrop'])
    .controller('mainCtrl', ['$scope', '$timeout',
        function ($scope, $timeout) {

            var nameList = ['Pierre', 'Pol', 'Jacques', 'Robert', 'Elisa'];
            var familyName = ['Dupont', 'Germain', 'Delcourt', 'bjip', 'Menez'];

            $scope.isLoading = false;
            $scope.rowCollection = [];


            function createRandomItem() {
                var
                    firstName = nameList[Math.floor(Math.random() * 4)],
                    lastName = familyName[Math.floor(Math.random() * 4)],
                    age = Math.floor(Math.random() * 100),
                    email = firstName + lastName + '@whatever.com',
                    balance = Math.random() * 3000;

                return {
                    firstName: firstName,
                    lastName: lastName,
                    age: age,
                    email: email,
                    balance: balance
                };
            }
            
            $scope.columns=['firstName', 'lastName','age','email','balance'];
            
            for(var i=0;i<50;i++){
              $scope.rowCollection.push(createRandomItem());
            }



        }
    ]);
.st-sort-ascent:before {
    content: '\25B2';
}

.st-sort-descent:before {
    content: '\25BC';
}

.lr-drop-target-before{
  border-left: 2px solid orange;
}

.lr-drop-target-after{
  border-right: 2px solid orange;
}



(function (ng) {
    'use strict';
    ng.module('smart-table',[]);
})(angular);

(function (ng, undefined) {
    'use strict';
    ng.module('smart-table')
        .controller('stTableController', ['$scope', '$parse', '$filter', '$attrs', function StTableController($scope, $parse, $filter, $attrs) {
            var propertyName = $attrs.stTable;
            var displayGetter = $parse(propertyName);
            var displaySetter = displayGetter.assign;
            var safeGetter;
            var orderBy = $filter('orderBy');
            var filter = $filter('filter');
            var safeCopy = copyRefs(displayGetter($scope));
            var tableState = {
                sort: {},
                search: {},
                pagination: {
                    start: 0
                }
            };
            var pipeAfterSafeCopy = true;
            var ctrl = this;

            function copyRefs(src) {
                return [].concat(src);
            }

            function updateSafeCopy() {
                safeCopy = copyRefs(safeGetter($scope));
                if (pipeAfterSafeCopy === true) {
                    ctrl.pipe();
                }
            }

            if ($attrs.stSafeSrc) {
                safeGetter = $parse($attrs.stSafeSrc);
                $scope.$watch(function () {
                    var safeSrc = safeGetter($scope);
                    return safeSrc ? safeSrc.length : 0;

                }, function (newValue, oldValue) {
                    if (newValue !== oldValue) {
                        updateSafeCopy()
                    }
                });
                $scope.$watch(function () {
                    return safeGetter($scope);
                }, function (newValue, oldValue) {
                    if (newValue !== oldValue) {
                        updateSafeCopy();
                    }
                });
            }

            /**
             * sort the rows
             * @param predicate function or string which will be used as predicate for the sorting
             * @param [optional] reverse if you want to reverse the order
             */
            this.sortBy = function sortBy(predicate, reverse) {
                tableState.sort.predicate = predicate;
                tableState.sort.reverse = reverse === true;
                tableState.pagination.start = 0;
                this.pipe();
            };

            /**
             * search matching rows
             * @param input the input string
             * @param predicate [optional] the property name against you want to check the match, otherwise it will search on all properties
             */
            this.search = function search(input, predicate) {
                var predicateObject = tableState.search.predicateObject || {};
                var prop = predicate ? predicate : '$';
                predicateObject[prop] = input;
                tableState.search.predicateObject = predicateObject;
                tableState.pagination.start = 0;
                this.pipe();
            };

            /**
             * this will chain the operations of sorting and filtering based on the current table state (sort options, filtering, ect)
             */
            this.pipe = function pipe() {
                var filtered = tableState.search.predicateObject ? filter(safeCopy, tableState.search.predicateObject) : safeCopy;
                filtered = orderBy(filtered, tableState.sort.predicate, tableState.sort.reverse);
                if (tableState.pagination.number !== undefined) {
                    tableState.pagination.numberOfPages = filtered.length > 0 ? Math.ceil(filtered.length / tableState.pagination.number) : 1;
                    filtered = filtered.slice(tableState.pagination.start, tableState.pagination.start + tableState.pagination.number);
                }
                displaySetter($scope, filtered);
            };

            /**
             * select a dataRow (it will add the attribute isSelected to the row object)
             * @param row the row to select
             * @param mode "single" or "multiple"
             */
            this.select = function select(row, mode) {
                var rows = displayGetter($scope);
                var index = rows.indexOf(row);
                if (index !== -1) {
                    if (mode === 'single') {
                        ng.forEach(displayGetter($scope), function (value, key) {
                            value.isSelected = key === index ? !value.isSelected : false;
                        });
                    } else {
                        rows[index].isSelected = !rows[index].isSelected;
                    }
                }
            };

            /**
             * take a slice of the current sorted/filtered collection (pagination)
             *
             * @param start index of the slice
             * @param number the number of item in the slice
             */
            this.slice = function splice(start, number) {
                tableState.pagination.start = start;
                tableState.pagination.number = number;
                this.pipe();
            };

            /**
             * return the current state of the table
             * @returns {{sort: {}, search: {}, pagination: {start: number}}}
             */
            this.tableState = function getTableState() {
                return tableState;
            };

            /**
             * Use a different filter function than the angular FilterFilter
             * @param filterName the name under which the custom filter is registered
             */
            this.setFilterFunction = function setFilterFunction(filterName) {
                filter = $filter(filterName);
            };

            /**
             *User a different function than the angular orderBy
             * @param sortFunctionName the name under which the custom order function is registered
             */
            this.setSortFunction = function setSortFunction(sortFunctionName) {
                orderBy = $filter(sortFunctionName);
            };

            /**
             * Usually when the safe copy is updated the pipe function is called.
             * Calling this method will prevent it, which is something required when using a custom pipe function
             */
            this.preventPipeOnWatch = function preventPipe() {
                pipeAfterSafeCopy = false;
            };
        }])
        .directive('stTable', function () {
            return {
                restrict: 'A',
                controller: 'stTableController',
                link: function (scope, element, attr, ctrl) {
                }
            };
        });
})(angular);

(function (ng) {
    'use strict';
    ng.module('smart-table')
        .directive('stSearch', ['$timeout', function ($timeout) {
            return {
                replace: true,
                require: '^stTable',
                scope: {
                    predicate: '=?stSearch'
                },
                link: function (scope, element, attr, ctrl) {
                    var tableCtrl = ctrl;
                    var promise = null;
                    var throttle = attr.stDelay || 400;

                    scope.$watch('predicate', function (newValue, oldValue) {
                        if (newValue !== oldValue) {
                            ctrl.tableState().search = {};
                            tableCtrl.search(element[0].value || '', newValue);
                        }
                    });

                    element.bind('input', function (evt) {
                        evt = evt.originalEvent || evt;
                        if (promise !== null) {
                            $timeout.cancel(promise);
                        }
                        promise = $timeout(function () {
                            tableCtrl.search(evt.target.value, scope.predicate || '');
                            promise = null;
                        }, throttle);
                    });
                }
            }
        }])
})(angular);

(function (ng) {
    'use strict';
    ng.module('smart-table')
        .directive('stSelectRow', function () {
            return {
                restrict: 'A',
                require: '^stTable',
                scope: {
                    row: '=stSelectRow'
                },
                link: function (scope, element, attr, ctrl) {
                    var mode = attr.stSelectMode || 'single';
                    element.bind('click', function () {
                        scope.$apply(function () {
                            ctrl.select(scope.row, mode);
                        });
                    });

                    scope.$watch('row.isSelected', function (newValue, oldValue) {
                        if (newValue === true) {
                            element.addClass('st-selected');
                        } else {
                            element.removeClass('st-selected');
                        }
                    });
                }
            }
        });
})(angular);

(function (ng, undefined) {
    'use strict';
    ng.module('smart-table')
        .directive('stSort', ['$parse', function ($parse) {
            return {
                restrict: 'A',
                require: '^stTable',
                link: function (scope, element, attr, ctrl) {

                    var predicate = attr.stSort;
                    var getter = $parse(predicate);
                    var index = 0;
                    var states = ['descent', 'ascent', 'natural'];

                    function reset() {
                        index = 0;
                        element
                            .removeClass('st-sort-ascent')
                            .removeClass('st-sort-descent');
                    }

                    function sort() {
                        index++;
                        var stateIndex = index % 2;
                        if (index % 3 === 0) {
                            //manual reset
                            ctrl.tableState().sort = {};
                            ctrl.tableState().pagination.start = 0;
                        } else {
                            ctrl.sortBy(predicate, stateIndex === 0);
                            element
                                .removeClass('st-sort-' + states[(stateIndex + 1) % 2])
                                .addClass('st-sort-' + states[stateIndex]);
                        }
                    }

                    if (ng.isFunction(getter(scope))) {
                        predicate = getter(scope);
                    }

                    element.bind('click', function sortClick() {
                        if (predicate) {
                            scope.$apply(sort);
                        }
                    });

                    if (attr.stSortDefault !== undefined) {
                        index = attr.stSortDefault === 'reverse' ? 1 : 0;
                        sort();
                    }

                    scope.$watch(function () {
                        return ctrl.tableState().sort;
                    }, function (newValue, oldValue) {
                        if (newValue !== oldValue) {
                            if (newValue.predicate !== predicate) {
                                reset();
                            }
                        }
                    }, true);

                }
            };
        }])
})(angular);

(function (ng) {
    'use strict';
    ng.module('smart-table')
        .directive('stPagination', function () {
            return {
                restrict: 'EA',
                require: '^stTable',
                scope: {},
                template: '<div class="pagination"><ul class="pagination"><li ng-repeat="page in pages" ng-class="{active: page==currentPage}"><a ng-click="selectPage(page)">{{page}}</a></li></ul></div>',
                replace: true,
                link: function (scope, element, attrs, ctrl) {

                    function isNotNan(value) {
                        return !(typeof value === 'number' && isNaN(value));
                    }

                    var itemsByPage = isNotNan(parseInt(attrs.stItemsByPage, 10)) == true ? parseInt(attrs.stItemsByPage, 10) : 10;
                    var displayedPages = isNotNan(parseInt(attrs.stDisplayedPages, 10)) == true ? parseInt(attrs.stDisplayedPages, 10) : 5;

                    scope.currentPage = 1;
                    scope.pages = [];


                    scope.$watch(function () {
                            return ctrl.tableState().pagination;
                        },
                        function () {
                            var paginationState = ctrl.tableState().pagination;
                            var start = 1;
                            var end;
                            var i;
                            scope.currentPage = Math.floor(paginationState.start / paginationState.number) + 1;

                            start = Math.max(start, scope.currentPage - Math.abs(Math.floor(displayedPages / 2)));
                            end = start + displayedPages;

                            if (end > paginationState.numberOfPages) {
                                end = paginationState.numberOfPages + 1;
                                start = Math.max(1, end - displayedPages);
                            }

                            scope.pages = [];
                            scope.numPages = paginationState.numberOfPages;

                            for (i = start; i < end; i++) {
                                scope.pages.push(i);
                            }


                        }, true);

                    scope.selectPage = function (page) {
                        if (page > 0 && page <= scope.numPages) {
                            ctrl.slice((page - 1) * itemsByPage, itemsByPage);
                        }
                    };

                    //select the first page
                    ctrl.slice(0, itemsByPage);
                }
            };
        });
})(angular);

(function (ng) {
    'use strict';
    ng.module('smart-table')
        .directive('stPipe', function () {
            return {
                require: 'stTable',
                scope: {
                    stPipe: '='
                },
                link: {
                    pre: function (scope, element, attrs, ctrl) {

                        if (ng.isFunction(scope.stPipe)) {
                            ctrl.preventPipeOnWatch();
                            ctrl.pipe = ng.bind(ctrl, scope.stPipe, ctrl.tableState());
                        }
                    }
                }
            };
        });
})(angular);
(function (ng) {
    'use strict';
    var module = ng.module('lrDragNDrop', []);

    module.service('lrDragStore', ['$document', function (document) {

        var store = {};

        this.hold = function hold(key, item, collectionFrom, safe) {
            store[key] = {
                item: item,
                collection: collectionFrom,
                safe: safe === true
            }
        };

        this.get = function (namespace) {
            var
                modelItem = store[namespace], itemIndex;
            if (modelItem) {
                itemIndex = modelItem.collection.indexOf(modelItem.item);
                return modelItem.safe === true ? modelItem.item : modelItem.collection.splice(itemIndex, 1)[0];
            } else {
                return null;
            }
        };

        this.clean = function clean() {
            store = {};
        };

        this.isHolding = function (namespace) {
            return store[namespace] !== undefined;
        };

        document.bind('dragend', this.clean);
    }]);

    function parseRepeater(scope, attr) {
        var
            repeatExpression = attr.ngRepeat,
            match;

        if (!repeatExpression) {
            throw Error('this directive must be used with ngRepeat directive');
        }
        match = repeatExpression.match(/^(.*\sin).(\S*)/);
        if (!match) {
            throw Error("Expected ngRepeat in form of '_item_ in _collection_' but got '" +
                repeatExpression + "'.");
        }

        return scope.$eval(match[2]);
    }

    function lrDragSrcDirective(store, safe) {
        return function compileFunc(el, iattr) {
            iattr.$set('draggable', true);
            return function linkFunc(scope, element, attr) {
                var
                    collection,
                    key = (safe === true ? attr.lrDragSrcSafe : attr.lrDragSrc ) || 'temp';

                collection = parseRepeater(scope, attr);

                element.bind('dragstart', function (evt) {
                    store.hold(key, collection[scope.$index], collection, safe);
                });
            }
        }
    }

    module.directive('lrDragSrc', ['lrDragStore', function (store) {
        return{
            compile: lrDragSrcDirective(store)
        };
    }]);

    module.directive('lrDragSrcSafe', ['lrDragStore', function (store) {
        return{
            compile: lrDragSrcDirective(store, true)
        };
    }]);

    module.directive('lrDropTarget', ['lrDragStore', function (store) {
        return {
            link: function (scope, element, attr) {

                var
                    collection,
                    key = attr.lrDropTarget || 'temp',
                    classCache = null;

                function isAfter(x, y) {
                    //check if below or over the diagonal of the box element
                    return (element[0].offsetHeight - x * element[0].offsetHeight / element[0].offsetWidth) < y;
                }

                function resetStyle() {
                    if (classCache !== null) {
                        element.removeClass(classCache);
                        classCache = null;
                    }
                }

                collection = parseRepeater(scope, attr);

                element.bind('drop', function (evt) {
                    var
                        collectionCopy = ng.copy(collection),
                        item = store.get(key),
                        dropIndex, i, l;
                    if (item !== null) {
                        dropIndex = scope.$index;
                        dropIndex = isAfter(evt.offsetX, evt.offsetY) ? dropIndex + 1 : dropIndex;
                        //srcCollection=targetCollection => we may need to apply a correction
                        if (collectionCopy.length > collection.length) {
                            for (i = 0, l = Math.min(dropIndex, collection.length - 1); i <= l; i++) {
                                if (!ng.equals(collectionCopy[i], collection[i])) {
                                    dropIndex = dropIndex - 1;
                                    break;
                                }
                            }
                        }
                        scope.$apply(function () {
                            collection.splice(dropIndex, 0, item);
                        });
                        evt.preventDefault();
                        resetStyle();
                        store.clean();
                    }
                });

                element.bind('dragleave', resetStyle);

                element.bind('dragover', function (evt) {
                    var className;
                    if (store.isHolding(key)) {
                        className = isAfter(evt.offsetX, evt.offsetY) ? 'lr-drop-target-after' : 'lr-drop-target-before';
                        if (classCache !== className && classCache !== null) {
                            element.removeClass(classCache);
                        }
                        if (classCache !== className) {
                            element.addClass(className);
                        }
                        classCache = className;
                    }
                    evt.preventDefault();
                });
            }
        };
    }]);
})(angular);
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){
      var 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;
};
/**
 * 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',
      
      //angular Material - Start
      '@angular/material': 'npm:@angular/material/bundles/material.umd.js',
      '@angular/cdk': 'npm:@angular/cdk/bundles/cdk.umd.js',
      '@angular/cdk/a11y': 'npm:@angular/cdk/bundles/cdk-a11y.umd.js',
      '@angular/cdk/bidi': 'npm:@angular/cdk/bundles/cdk-bidi.umd.js',
      '@angular/cdk/coercion': 'npm:@angular/cdk/bundles/cdk-coercion.umd.js',
      '@angular/cdk/collections': 'npm:@angular/cdk/bundles/cdk-collections.umd.js',
      '@angular/cdk/keycodes': 'npm:@angular/cdk/bundles/cdk-keycodes.umd.js',
      '@angular/cdk/observers': 'npm:@angular/cdk/bundles/cdk-observers.umd.js',
      '@angular/cdk/overlay': 'npm:@angular/cdk/bundles/cdk-overlay.umd.js',
      '@angular/cdk/platform': 'npm:@angular/cdk/bundles/cdk-platform.umd.js',
      '@angular/cdk/portal': 'npm:@angular/cdk/bundles/cdk-portal.umd.js',
      '@angular/cdk/rxjs': 'npm:@angular/cdk/bundles/cdk-rxjs.umd.js',
      '@angular/cdk/scrolling': 'npm:@angular/cdk/bundles/cdk-scrolling.umd.js',
      '@angular/cdk/table': 'npm:@angular/cdk/bundles/cdk-table.umd.js',
      '@angular/cdk/testing': 'dist/bundles/cdk/cdk-testing.umd.js',
      //angular Material - End

      // 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.3.2/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
*/
import { Component, Input  } from '@angular/core';
import {DragDropService} from './app.dragdrop.service';

@Component({
  selector: 'app-root',
  templateUrl:  'app/app.component.html',
  styleUrls: [ 'app/app.style.css' ]
})
export class AppComponent {
   title = 'AFEWS Modernization';
   
  constructor(public _dragDrop: DragDropService) { }
    
   ngOnInit() {
      //this.menus = this._menuService.getMenuList();
      this._dragDrop.fillTableData();
  } 
  
  public getColumns():Promise<String[]>{
    return this._dragDrop.columns;
  }
  
  public getRowCollection():Promise<String[]>{
    return this._dragDrop.rowCollection;
  }
  
   private addMore(){
     this._dragDrop.addMore();
  }
  
}
<div class="mainContainer">
  
  <div class="citiBrandingNav">
    <h4>BRAND HEADER</h4>
    <button type="button" class="btn btn-primary pull-right" id="addMore" (click)="addMore()">Add More</button>
    <button type="button" class="btn btn-primary pull-right" id="changecol" (click)="changeColumns()">Change Columns</button>
  </div>
    
  <div id="wrapper">
    <div class="table-container">
      <table st-table="rowCollection" class="table table-striped">
  	<thead>
	<tr>
	 <!--*ngFor="let AccountList of getListSearchResult(); let i = index;" class="editRecord" -->
		<th lr-drag-src="headers" lr-drop-target [dragdrop] =_dragDrop *ngFor="let col of getColumns()" id={{col}} st-sort="{{col}}">
		  <div data-toggle="tooltip" data-placement="top" title="Drag & Drop">
		    <md-tooltip id="slider-tooltip" style="-ms-transition: none; -o-transition: none; -webkit-transition: none; transition: none;"></md-tooltip>
		    {{col}}
		  </div>
		</th>
	</tr>
	<!--tr>
		<th>
			<input st-search="firstName" placeholder="search for firstname" class="input-sm form-control" type="search"/>
		</th>
		<th colspan="4">
			<input st-search placeholder="global search" class="input-sm form-control" type="search"/>
		</th>
	</tr-->
	</thead>
	<tbody>
	<tr *ngFor="let row of getRowCollection()">
		<td *ngFor="let col of getColumns()">{{row[col]}}</td>
	</tr>
	</tbody>
</table>
</div>
<div ng-show="isLoading" class="loading-indicator"></div>

</div>
  
</div>

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

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

platformBrowserDynamic().bootstrapModule(AppModule);
import { NgModule,NO_ERRORS_SCHEMA }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }   from '@angular/forms';
import { HttpModule }    from '@angular/http';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
//import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {MdInputModule, MdSelectModule, MdDatepickerModule, MdNativeDateModule} from '@angular/material';


import { AppComponent }         from './app.component';
import { HighlightDirective }         from './app.highlight.directive';
import { DropTarget }         from './app.droptarget.directive';
import { DragDropService }         from './app.dragdrop.service';
/*import { routing }        from './app.routing';
import { AccountComponent } from './account/account.component';
import { AccountDetailsComponent } from './account/accountdetails.component';
import { AppMenu }         from './menu/app.menu';
import { MenuService }         from './menu/app.menu.service';
import { DragDropService }         from './app.dragdrop.search';
import { AppSearchResult }         from './account/app.searchresult';
import { SearchService }         from './account/app.search.service';
import { SearchTemplate }         from './account/app.searchtemplate';
*/

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    //HttpModule,
    //routing,
    BrowserAnimationsModule,
    MdInputModule,
    MdSelectModule,
    MdDatepickerModule,
    MdNativeDateModule,
  ],
  declarations: [
    AppComponent,
    HighlightDirective,
    DropTarget,
    //AccountComponent,
    //AccountDetailsComponent,
    //AppMenu,
    //AppSearch,
    //AppSearchResult,
    //SearchTemplate,
  ],
  providers: [DragDropService ],
  bootstrap: [ AppComponent ],
  schemas:      [ NO_ERRORS_SCHEMA ]
})
export class AppModule { }
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
 
@Directive({
  selector: '[lr-drag-src]'
})
export class HighlightDirective {
  constructor(private el: ElementRef) { }
 
  @HostListener('mouseenter') onMouseEnter() {
    this.highlight('yellow');
  }
 
  @HostListener('mouseleave') onMouseLeave() {
    this.highlight(null);
  }
 
  private highlight(color: string) {
    this.el.nativeElement.draggable = true;
    if(color !=null){
      this.el.nativeElement.dataToggle="tooltip";
      this.el.nativeElement.dataPlacement="top"; 
      this.el.nativeElement.title="Drag & Drop Columns";
      this.el.nativeElement.style.backgroundColor = color;
      this.el.nativeElement.style.borderBottom = "2px solid #0073ff";
	    this.el.nativeElement.style.borderRight = "3px solid #0073ff";
    }else{
      this.el.nativeElement.style.backgroundColor = color;
      this.el.nativeElement.style.borderBottom = null;
	    this.el.nativeElement.style.borderRight = null;
    }
  }
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
import {DragDropService} from './app.dragdrop.service';

@Directive({
  selector: '[lr-drop-target]'
})
export class DropTarget {
  constructor(private el: ElementRef) { }
  @Input() dragdrop: DragDropService;
  //private dragCol:String =  "";
  //private dropCol:String =  "";
  
  ngOnInit() {
      //this.setEvents();
  } 
  
  @HostListener('dragover', ['$event']) onDragOver(event: Event) {
    //alert("Drag Over");
    event.preventDefault();
    //console.log("Drag Over" + event.target.id);
    return false;
    //console.log( event.target.id)
  }
 
  @HostListener('drop', ['$event']) onDrop(event: Event) {
    //console.log("Drop " + event.target.id);
    this.dragdrop.dropCol = event.target.id;
    //console.log(this.dragdrop.dragCol + "***" + this.dragdrop.dropCol);
    this.dragdrop.changeColumns();
  }
  
  @HostListener('dragstart', ['$event']) onDropLeave(event: Event) {
    //event.preventDefault();
    //console.log("dragstart " + event.target.id);
    this.dragdrop.dragCol = event.target.id;
    //return false;
  }
  
/*
  private highlight(color: string) {
    this.el.nativeElement.style.backgroundColor = color;
    this.el.nativeElement.draggable = true;
  }
  */

}
import {Injectable} from '@angular/core';
//import {Http} from '@angular/http';

/*
import { AccountList } from './AccountList';
import { AccountListRec } from './app.AccountList.sample';
import { MyAccountListRec } from './app.MyAccountList.sample';
import { AccountListColumns } from './AccountListColumns';
import { AccountListColumnValues } from './app.AccountListColumns.Sample';
*/
@Injectable()
export class DragDropService {

  //searchResult : AccountList[];
  //accountListColumns : AccountListColumns[];
  //newSearchFlag : bool;
  private isLoading : boolean = false;
  private rowCollection : String[] = []; 
  private columns : String[] = [];   
  public dragCol : String;
  public dropCol : String;
   
  constructor () {}
  
  private fillTableData() {
    this.isLoading = false;
    this.rowCollection = [];

    this.columns=['firstName', 'lastName','age','email','balance'];
            
    for(var i=0;i<10;i++){
      this.rowCollection.push(this.createRandomItem());
    }
  }
  
  private addMore(){
     for(var i=0;i<10;i++){
      this.rowCollection.unshift(this.createRandomItem());
    }
  }
  
  public changeColumns(){
    let dragColPos  : Number = -1;
    let dropColPos  : Number = -1;
    
    for(var i=0;i<this.columns.length;i++){
      if(this.columns[i] == this.dragCol ){
        dragColPos = i;
      }
      if(this.columns[i] == this.dropCol ){
        dropColPos = i;
      }
    }
    
    //console.log(this.dragCol + " -- " + this.dropCol);
    //console.log(dragColPos + " -- " + dropColPos);
    
    this.columns[dragColPos] = this.dropCol;
    this.columns[dropColPos] = this.dragCol;
    
    //console.log(this.columns);
    
    //this.columns=['age', 'lastName','firstName','email','balance'];
  }
  
//getTableDisplayData(pos:String): Promise<String>         
  private createRandomItem():Promise<String[]> {
    var nameList = ['Pierre', 'Pol', 'Jacques', 'Robert', 'Elisa'];
    var familyName = ['Dupont', 'Germain', 'Delcourt', 'bjip', 'Menez'];

    var
        firstName = nameList[Math.floor(Math.random() * 4)],
        lastName = familyName[Math.floor(Math.random() * 4)],
        age = Math.floor(Math.random() * 100),
        email = firstName + lastName + '@whatever.com',
        balance = Math.random() * 3000;

    return {
        firstName: firstName,
        lastName: lastName,
        age: age,
        email: email,
        balance: balance
    };
  }  

	getNewSearchFlag():Promise<bool>{
	  return this.newSearchFlag;
	}

	setNewSearchFlag(searchFlag:bool){
	  this.newSearchFlag = searchFlag;
	}
	
}