Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 + PrimeNG - How to reset dataTable when the underlying data changes?

I'm binding an array of Cell objects to a PrimeNG DataTable:

.html:

  <p-dataTable [value]="_cells" [responsive]="true" [globalFilter]="gb">
        <p-column field="id" header="id" sortable="true"></p-column>
        <p-column field="name" header="name" sortable="true" ></p-column>         
    </p-dataTable>

.ts:

ngOnInit() {
        var self = this;
        // Capture the id in the URL
        this._route.params.subscribe(params => {
            self._stationId= params['id'];

            this._dataService
                .GetAllCells(self._stationId)
                .subscribe((data:Cell[]) => this._cells = data,
                    error => alert(error),
                    () => console.log('Retrieved cells'));
        });
    }

So I found out the dataTable has a reset() method to clear the sorting/filtering/selection state. I need to call it whenever the URL parameter changes and new data is being load.

But how can I reference the dataTable and call the reset() method from inside the ngOnInit() method?

like image 832
user66875 Avatar asked Sep 12 '16 13:09

user66875


2 Answers

You could leverage the @ViewChild annotation:

export class MyComponent implements OnInit {
    @ViewChild(DataTable) dataTableComponent: DataTable;

    // ...

    ngOnInit() {
        this.dataTableComponent.reset();
    }
}
like image 123
rinukkusu Avatar answered Nov 03 '22 21:11

rinukkusu


Thanks to rinukkusu. In newer versions of primeng it works as this:

//Just replace DataTable with Table
import {Table} from 'primeng/components/table/table';

export class MyComponent implements OnInit {
   @ViewChild(Table) tableComponent: Table;

   // ...

ngOnInit() {
    this.tableComponent.reset();
}
}
like image 36
Mostafa Karamizade Avatar answered Nov 03 '22 21:11

Mostafa Karamizade