Angular2 + PrimeNG - How to reset dataTable when t

2020-06-19 07:19发布

问题:

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?

回答1:

You could leverage the @ViewChild annotation:

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

    // ...

    ngOnInit() {
        this.dataTableComponent.reset();
    }
}


回答2:

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();
}
}