3

I'm trying to append a button to an angular table.

It shows the button but when a click on it, it doesn't fire the event.

This is my table:

<table mat-table [dataSource]="GetGridData()">
  <!-- Rest removed for brevity.. -->

  <ng-container matColumnDef="Products">
    <th mat-header-cell *matHeaderCellDef> Products </th>
    <td mat-cell *matCellDef="let element">
      <button mat-raised-button (click)="OnGetAllProducts(element.CategoryId)">See all products</button>
    </td>
  </ng-container>

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

And this is what I've got on my ts:

export class DashboardComponent {
    // Rest of code removed for brevity.         

    // Row's events.
    //--------------
    OnGetAllProducts(categoryId: number) {
        alert("Listed");
    }
}

And this is my model:

export class Category {
    public CategoryId: number;
    public CategoryName: string;
}
10
  • Do you see any error in the console? Commented May 10, 2018 at 18:21
  • 1
    It should work actually, Is See all products button visible in UI? Commented May 10, 2018 at 18:21
  • No, I don't see any error. Yea, it should. I still can't see why it doesn't. Been half a day on that. Commented May 10, 2018 at 18:22
  • Yea, it actually is visible. @BasavarajBhusani Commented May 10, 2018 at 18:23
  • One thing that I noticed is that, if i take the button out of the table, it works perfectly. It gets screwed up when I place it inside of the table. Commented May 10, 2018 at 18:23

2 Answers 2

4

It's the dataSource. Your GetGridData() function is running constantly because you placed it in the template, which is re-rendering the table endlessly, which is why that's a bad practice. Instead, store the result in a variable and that's what you should pass as your dataSource.

1
  • Correct in my case. Was re-rendering the table as the button was clicked and therefore interrupting the click process. I've changed my getter to cache the array variable and return the same object unless the deriving parameters change. Thanks!
    – Ralpharoo
    Commented Dec 24, 2018 at 2:28
1

TLDR; verify correctness of styles

As many people can encounter similar problem and land here (like myself) I hope it wouldn't be a big offense when I post solution that worked for me in order to help next generations.

@BasavarajBhusani and others asked really good question, if button is really visible from UI.

The truth is that despite being physically visible, my button slipped out of borders of the parent element. After fixing styles by making parent element to dynamically adjust its size, it started to work well.

It is strange but the same layout worked well in AngularJS (1.X) but stopped after porting into Angular 6.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.