1

So, if the row.id has value(say: id_1313) I want to add a click event to mat-row else I need to simply display the mat-row.

I'll provide a sample code of what I actually did

app.component.html

<table
   mat-table
   [dataSource]="dataSource"
   width="100%"
 >

 <ng-container matColumnDef="date">
     <th mat-header-cell *matHeaderCellDef>
          Date
     </th>
     <td mat-cell *matCellDef="let element">{{ element.date }}</td>
 </ng-container>

 <ng-container *matRowDef="let row; columns: displayedColumns">
      <div
         *ngIf="
         row.id;
         then hasId;
         else notHasId
         "
        ></div>
       <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
        <tr
          #hasId
          mat-row
          (click)="hasId()"
          *matRowDef="let row; columns: displayedColumns"
        ></tr>
        <tr
          #notHasId
          mat-row
          *matRowDef="let row; columns: displayedColumns"
        ></tr>
  </ng-container>
        

I know the approach I tried is not gonna work, any ideas to do changes only on mat-row. I don't want to use *ngIf for each column value in the ng -container

EDIT

I found the answer after some research. We can enable the click method using ternary operator. The demo code is below.

<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr
   mat-row
   *matRowDef="let row; columns: displayedColumns"
   (click)="row.id != null ? displayDetails(row) : null"
></tr>
Tamilvanan
  • 23
  • 2
  • 7
  • 1
    Would it not be easier to add the `(click)` to all of the rows and then simply have the function `return;` if the row has no id? – akseli Mar 16 '23 at 16:46
  • I have solution for that, but I want to know is there a way to solve it like this? – Tamilvanan Mar 16 '23 at 16:51
  • 1
    you can use also `(click)="row.id!=null && displayDetails(row)"`. Rememeber that Javascrip is "short circuit avaluation" (If first condition is not fullfilled, don't execute the second one) – Eliseo Mar 21 '23 at 12:24
  • @Eliseo Thank you, this improves the readability as well. – Tamilvanan Mar 22 '23 at 16:02

0 Answers0