0

I am a beginner ,I have a mat-table :

<table mat-table [dataSource]="list_equipment" matSort style="width: 100%;"> 
    <!-- id Column -->
    <ng-container matColumnDef="id">
      <th mat-header-cell *matHeaderCellDef style="text-align: center !important;" mat-sort-header> id </th>
      <td mat-cell *matCellDef="let list_equipment" style="text-align: center;"> {{list_equipment.id}} </td>
    </ng-container>
     <!-- CaptionCode Column -->
     <ng-container matColumnDef="Caption">
      <th mat-header-cell *matHeaderCellDef style="text-align: center !important;" mat-sort-header> caption</th>
      <td mat-cell *matCellDef="let list_equipment" style="text-align: center;"> {{list_equipment.Caption}} </td>
    </ng-container>
    ...
    <tr mat-header-row *matHeaderRowDef="displayedColumnsequipment"></tr>
    <!-- <tr mat-row *matRowDef="let row; columns: displayedColumnsequipment;" (click)="highlight(row)" [ngClass]="{'highlightTableColor': selectedRowIndex == row.position}"></tr> -->
    <tr mat-row class="table-row" tabindex="1" *matRowDef="let row; columns: displayedColumnsequipment;"  (click)="highlight(row)"></tr>
  </table>
  <mat-paginator [pageSizeOptions]="[10, 20, 50]" showFirstLastButtons></mat-paginator>

In TypeScript I write below code:

highlight(row){
  this.selectedRow=row;
  console.log(this.selectedRow); 
}

The problem is that wherever I use the {{selectedRow.id}}in html code, it gives this error in console :Cannot read property 'id' of undefined

1
  • 4
    This happens because the property selcetedRow is not initialized and can be null. So you should consider this case. Easies way to do is {{selectedRow?.id}}. Commented May 30, 2021 at 13:17

1 Answer 1

2

you are defining the value which is not initialized so you have to set the value as "Safe Navigation Operator" "?"

                 {{selectedRow.id}} to {{selectedRow?.id}}

so this condition will not break your code and will not give you undefined or null value.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.