0

I would like to be able to increment the columns when added dynamically in an angular material table. I am using the add column method to create a new column from the Angular material documentation. https://material.angular.io/components/table/examples

The columns get added, but I need them to increment and display a column number.w

2 Answers 2

1

When we use a material-table we need take account two things:

  1. The source
  2. The displayed Columns

As you want to create a series of inputs, you need relationate the inputs with variables, what about use a FormArray?

Well, the things are easy if we thing in a data source like

[
{position: 1, name: 'Hydrogen',
 col0:new FormControl(),col1:new FormControl(),
 weight: 1.0079, symbol: 'H'},
{position: 2, name: 'Helium',
 col0:new FormControl(),col1:new FormControl(),
 weight: 4.0026, symbol: 'He'},
...
]

At first our form array is an Array with so many formGroups as rows has the table

formArray=new FormArray(ELEMENT_DATA.map(x=>new FormGroup({})))

I chooose help me using three arrays, ColumnsBefore,ColumnsAfter and ColumnsArray, so displayedColumns becomes like

this.displayedColumns=this.columnsBefore.map(x=>x.name)
                    .concat(this.columnsArray.map(x=>x.name))
                    .concat(this.columnsAfter.map(x=>x.name))

When we add a column, we need add a new control to each element of the array, add to the source a reference of the control create, add an element to ColumnsArray and refresh displayedColumns.(The name of the control will be, e.g. col0,col1,...)

  addColumn()
  {
    let count=this.columnsArray.length
    this.formArray.controls.forEach((group:FormGroup,index)=>{
         group.addControl("col"+count,new FormControl())
         this.dataSource[index]["col"+count]=this.formArray.at(index).get("col"+count)
    })

    this.columnsArray.push({name:"col"+count,title:"Round "+(count+1)})
    this.displayedColumns=this.columnsBefore.map(x=>x.name)
                        .concat(this.columnsArray.map(x=>x.name))
                        .concat(this.columnsAfter.map(x=>x.name))
  }

To remove the column, we need remove the control of each element of FormArray, remove the element of columnsArray and refresh displayedColumns

  removeColumn()
  {
    let count=this.columnsArray.length-1
    if (count>=0)
    {
      this.columnsArray.pop()
      this.formArray.controls.forEach(group=>
      {
        (group as FormGroup).removeControl("col"+count)
      })
      this.displayedColumns=this.columnsBefore.map(x=>x.name)
                        .concat(this.columnsArray.map(x=>x.name))
                        .concat(this.columnsAfter.map(x=>x.name))
    }
  }

It's not necesary remove the element form the source

The .html is (see why we use three arrays)

<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
    <ng-container *ngFor="let column of columnsBefore" [matColumnDef]="column.name">
        <th mat-header-cell *matHeaderCellDef>{{column.title}}</th>
        <td mat-cell *matCellDef="let element"> {{element[column.name]}} </td>
    </ng-container>

    <ng-container *ngFor="let column of columnsArray" [matColumnDef]="column.name">
        <th mat-header-cell *matHeaderCellDef>{{column.title}}</th>
        <td mat-cell *matCellDef="let element">
            <input style="width:2rem;margin-rigth:.5rem" [formControl]="element[column.name]"/>
        </td>
    </ng-container>

    <ng-container *ngFor="let column of columnsAfter" [matColumnDef]="column.name">
        <th mat-header-cell *matHeaderCellDef>{{column.title}}</th>
        <td mat-cell *matCellDef="let element"> {{element[column.name]}} </td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

The stackblitz

TODO, after create the formArray, subscribe to formArray.valueChanges to put the totals in a columns

Sign up to request clarification or add additional context in comments.

1 Comment

This is great. Thank you.
1

Use the index in *ngFor:

*ngFor="let column of displayedColumns; let i = index;"

And then increment it by 1:

<button mat-raised-button (click)="addColumn()"> Add column </button>
<button mat-raised-button (click)="removeColumn()"> Remove column </button>
<button mat-raised-button (click)="shuffle()"> Shuffle </button>

<table mat-table [dataSource]="data" class="mat-elevation-z8">
  <ng-container [matColumnDef]="column" *ngFor="let column of displayedColumns; let i = index;">
    <!-- HERE -->
    <th mat-header-cell *matHeaderCellDef> {{ i + 1 }} {{column}} </th>
    <td mat-cell *matCellDef="let element"> {{element[column]}} </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="columnsToDisplay"></tr>
  <tr mat-row *matRowDef="let row; columns: columnsToDisplay;"></tr>
</table>


<!-- Copyright 2019 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 -->

Here's a Working Sample StackBlitz for your ref.

1 Comment

Thank you this is helpful, but I am running into a problem where I get an error, that says "Duplicate column definition name provided: "id"." when there are named columns included with the incremented columns. I want the first few columns to be named columns and only a set to be incremented for the purposes of creating rounds for a tournament. I have attached the original table I am referencing. <img src="imgur.com/a/SDJQGzP">

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.