Refresh angular mat table dynamically by adding a row?

Discussão em 'Angular' iniciado por Olivier, Janeiro 21, 2025.

  1. Olivier

    Olivier Guest

    I know that there have been answers on this subject, despite everything, I struggle to add a new row to a material datasource. Here’s the code I’m trying to make works:

    ts:

    public dataSource = new MatTableDataSource(this.piecesJointes);
    public piecesJointes: any[] = [];

    public refresh(): void {
    const pjFinal = { libelle: 'testLibelle', nom: 'testNom };
    this.piecesJointes.push(pjFinal);
    this.dataSource = new MatTableDataSource(this.piecesJointes);
    console.log(this.dataSource) // display the correct dataSource
    }


    this refresh() method is called by a fileSelected event in HTML:

    (fileSelected)="refresh()"


    And here's the material table:

    <table
    mat-table
    [dataSource]="dataSource"
    class="mat-elevation-z8 demo-table"
    >
    <!-- libelle Column -->
    <ng-container matColumnDef="libelle">
    <th mat-header-cell *matHeaderCellDef>
    column1
    </th>
    <td mat-cell *matCellDef="let element">{{ element.libelle }}</td>
    </ng-container>

    <!-- nom doc Column -->
    <ng-container matColumnDef="nomDocument">
    <th mat-header-cell *matHeaderCellDef>
    column2
    </th>
    <td mat-cell *matCellDef="let element">{{ element.nom }}</td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumnsJustifs"></tr>
    </table>


    Thanks

    Continue reading...

Compartilhe esta Página