javascriptangularsmart-table

How would i dynamically populate the columns of ng2-smart-table in angular 4


I was relatively new to Angular and had serious issues before i figured out a way to do this. use this link to preview the solution

 <https://plnkr.co/edit/OtJI13uA89caf8TG5lbI?p=preview>?

Solution

  • To dymanically populate your ng2-smart-table, you may follow the steps below. 1. Import smart table component in your module. import { LocalDataSource } from "ng2-smart-table";

    2.add the following code to your class.

         @Component({
          selector: 'my-app',
          template: `
            <div>
              <h2>Hello {{name}}</h2>
              <button (click)="addColumn()">Add Column</button>
              <ng2-smart-table [settings]="settings" [source]="source"></ng2-smart-table>
            </div>
    
          `,
        })
         export class ResultComponent implements OnInit
          {
          source: LocalDataSource;
          i = 0;
          settings;
          mySettings = {
          mode: 'inline',
          actions: {
               delete:false,
            },
          add: {
          confirmCreate: true,
          },
          delete: {
          confirmDelete: true,
          },
          edit: {
          confirmSave: true,
          },
          columns: {
    
          }
          };
    
       //method that adds the column. You can use trigger events to do this
        public addColumn() {
              this.mySettings.columns["new column " + this.i] = { title: 'new column 
             ' + this.i.toString()};
              this.settings = Object.assign({}, this.mySettings);
              this.i++;
          }
    
         }