[FIXED] PrimeNG p-table methods keeps firing on table click

Issue

I have a p-table with a set of 12 items (which are not lazy loaded).
Some of this data has methods computing different things in HTML. The problem is that all these methods keep being called on every table click, not matter where I click. Those methods are NOT binded to the click event – they are just returning some data as string etc.

Is there any way to disable that propagation, so my methods are not called on every table click? I just want to render this table once and don’t change anything.
I don’t need to use onLazyLoad, because the data is small enough that I can load it in OnInit.

p-table looks somewhat like that

  <p-table [value]="data"
       dataKey="id"
       [rowHover]="true"
       [filterDelay]="0"> 
          <div>{{ calculateCurrentTime() }}</div>
  </p-table>

And calculateCurrentTime() is firing every time I click on the table (no matter when). I tried setting lazy="true" won’t help, but without success.

It’s important to note that inside this table I have a button which I want to be able to click.

Solution

The below issue is occurred due to calling the function from the template, we should not call a function in the template.

this method is getting called EVERY time I click on the table (no
matter when)

An alternative way to call the function is in ngOnInit() and assign it in a variable. It will get the current time during initiating the table component.
Example:

ngOnInit() {
 this.getTabledata();
}

public getTabledata() {
 this.data = response.data;
 this.data.forEach(item => {
   // Update only below particualar object in the data.
   if (item.id = 13) {
    item.currentTime = this.calculateCurrentTime(item);
   }
 });

}

In Template:

  <p-table [value]="data"
       dataKey="id"
       [rowHover]="true"
       [filterDelay]="0"> 
         // You can get this item by looping the data. I am just adding the condition
          <div>{{ item.currentTime ? item.currentTime : '' }}</div>
  </p-table>

Ref Link for Why You Should Never Use Methods Inside Templates in Angular:

https://betterprogramming.pub/why-you-should-never-use-methods-inside-templates-in-angular-497e0e11f948

Thanks

Answered By – Jai Saravanan

Answer Checked By – Terry (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published