angularprimengprimeng-table

PrimeNG Table filter: Cannot set properties of undefined (setting 'filters')


I need to save the filtering state of the primeng table. I save the state to the service, there is no problem with that. I also receive data from the service, I display them in the console, everything is fine. But when I try to change the current filtering state to the one I received from the service, I get an error.

ERROR TypeError: Cannot set properties of undefined (setting 'filters')

Component.ts

  ngOnInit(): void {
    const savedFilters = this.fundingService.getDataState();
    console.log("savedFilters: ", savedFilters); // all is good
    if (savedFilters){
      this.dt.filters = savedFilters; //error
    }
  }

  seeDetailedData(id: string) {
    const filters: FilterMetadata[] | FilterMetadata = this.dt.filters;
    this.fundingService.setDataState(filters);
    this.router.navigate(['test', id]);
  }

Component.html

<p-table #dt [value]="data" [paginator]="data.length > 10" [rows]="10" [globalFilterFields]="['name', 'surname']" (sortFunction)="sortPool($event)" [customSort]="true">
 <!-- ... -->
</p-table>

Service.ts

  private state: any = {};

  getDataState(): any {
    return this.state;
  }

  setDataState(newState: any) {
    this.state = newState;
  }

Solution

  • Filter state assignment should be implemented in ngAfterViewInit instead of ngOnInit

    Component.ts

      ngAfterViewInit(): void {
        const savedFilters = this.fundingService.getDataState();
        console.log("savedFilters: ", savedFilters);
        if (savedFilters){
          this.dt.filters = savedFilters;
        }
      }
    

    I think this is related to the fact that ViewChild becomes accessible only after the directive is initialized in the component template, and ngAfterViewInit is called right after its initialization.