Search code examples
angularangular-materialangular-material-table

Button within Angular Material Table not working


I have the following Angular Material Table setup:

    <table mat-table [dataSource]="getItems()">
      <ng-container matColumnDef="delete">
        <th mat-header-cell *matHeaderCellDef></th>
        <td mat-cell *matCellDef="let tariff">
          <button type="button" mat-button color="primary" (click)="test()">Delete</button>
        </td>
      </ng-container>

      ...

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

  test() {
    console.log('test');
  }

If I click on the delete button the test() method isn't called. If I remove the 'mat-button' directive the button suddenly works.

I have other material design buttons on the form so it isn't a module import issue.

What is happening here?

StackBlitz to show the problem: https://stackblitz.com/edit/angular-fgkduw?file=src%2Fapp%2Fapp.component.html


Solution

  • Changing [dataSource] to an array instead of a function solves the problem.

    https://stackblitz.com/edit/angular-ezanza?embed=1&file=src/app/app.component.html

    It may be a strange behaviour caused by using mat-table in an inappropriate way.

    Angular Material Table expects [dataSource] to be an array or, for more complex applications, a DataSource instance.

    https://material.angular.io/components/table/overview#1-write-your-mat-table-and-provide-data