Search code examples
angularprimeng

Lazy loading in primeng table


I have a component with p-dropdown and p-table. When I choose item in the dropdown i would like to lazy load data in my p-table in this component. Is it possibile? When I'm trying i have only lazy load on init whole component.

https://stackblitz.com/edit/primeng-tablelazy-demo-lwb4no?file=src%2Fapp%2Fapp.component.ts


Solution

  • There are two problems with the example you provided:

    1. An error is thrown because the event parameter in your onChange function is undefined. To fix this you need to call the function in the template like this:
    <p-dropdown
      [options]="['customers_a', 'customers_b', 'customers_c']"
      (onChange)="onChange($event)"
    ></p-dropdown>
    

    (Mind the dollar sign in the parameter name. You can find more about this in the docs)

    1. You are not providing a lazy load event to the loadCustomers method. Instead you are passing the event from the dropdown which does not have the required attributes.

    So instead of calling the loadCustomers method like this:

        this.loadCustomers(event, this.selectedCustomers);
    

    You can either call the reset method on the table or manually get the lazyLoad metadata from the table. In order to do this you need a reference to the table in you component class. This can be archive with the ViewChield decorator.

    Option 1:

      @ViewChild(Table)
      table: Table;
    
      onChange(event) {
        this.selectedCustomers = event.value;
        this.table.reset()
      }
    

    Option 2:

      @ViewChild(Table)
      table: Table;
    
      onChange(event) {
        this.selectedCustomers = event.value;
        this.loadCustomers(this.table.createLazyLoadMetadata(), this.selectedCustomers)
      }