Search code examples
angularprimeng

difference between method and class field when setting table value


I had a problem where I couldn't select and copy text from a table because the table was refreshed and rendered every time I clicked on it. When I change version one where I use the method to set the table value to version two where I use the class field, the problem is solved. Could someone explain to me why? This table was placed in a modal dialog.

Component:

@Input() details: any;
protected metadata: any;

ngOnInit(): void {
  this.metadata = this.getMetadata();
}

getMetadata() {
  return [{
    date: this.details.revisionInfo.timestamp
  }];
}

Version1:

<p-table [value]="getMetadata()">
  <ng-template pTemplate="header">
    <tr>
      <th scope="col">Date</th>
    </tr>
  </ng-template>
  <ng-template pTemplate="body" let-rowData>
    <tr>
      <td>
        {{rowData.date}}
      </td>
    </tr>
  </ng-template>
</p-table>

Version2:

<p-table [value]="metadata">
  <ng-template pTemplate="header">
    <tr>
      <th scope="col">Date</th>
    </tr>
  </ng-template>
  <ng-template pTemplate="body" let-rowData>
    <tr>
      <td>
        {{rowData.date}}
      </td>
    </tr>
  </ng-template>
</p-table>

Solution

  • while you are doing getMetadata() the method is called on every change detection. It may be not an issue at all, but it could also bring huge performance degradation for your component. It depends on the exact cases.

    If you can afford to learn and understand change detection - do it and you will be able to distinguish between cases where it is possible to leave a method call in the template. But in general it is better to save value as a component property and refer to it in the template.