Search code examples
angularangular-materialag-grid-angular

how would a user be able to add a column and name it anything they want to my table


so using an angular framework...and angular material. I want the table to be have customised tables of data, in which users build the structure of the tables by adding columns to their tables and then adding items which are the tables rows...

How can i develop my component where a user would add a new column, and be able to give it any name they want?


Solution

  • First, create an input element, where the user would input the column name. Then, you can create an array of strings columnsToDisplay and loop through it in your ng-container using *ngFor.

    <table mat-table [dataSource]="dataSource"
      <ng-container matColumnDef="{{column}}" *ngFor="let column of 
        columnsToDisplay">
            <th mat-header-cell *matHeaderCellDef> {{column}} </th>
            <td mat-cell *matCellDef="let data"> {{data}} </td>
      </ng-container>
      <tr mat-header-row *matHeaderRowDef="columnsToDisplay"></tr>
      <tr mat-row *matRowDef="let row; columns: columnsToDisplay"></tr>
    </table>
    

    Then you only need to append the user's input to this array.