Angular 2 Sort table columns

I assume you are loading the data (selectedData) for this template asynchronously in the component’s class, so at the start it’s not yet returned form the service, hence selectedData = undefined.

There are several things you can do to mitigate that:

1. Initialize the data in the component

Set the selectedData class property to an empty array so when the pipe runs its input will be an array even if the backend data is not yet returned.

export class MyComponent {
    selectedData = [];
}

2. Prevent evaluation of this part of the template with *ngIf

Don’t render the template part with said pipe until you have the array.

<table *ngIf="selectedData">
  <!-- ... -->
  <tr *ngFor="let x of selectedData  | orderBy: {property: column, direction: direction}">
</table>

3. Make the pipe “empty-input-safe” by providing a default input

This should be the preferred solution because with that you won’t have to remember to employ any special logic (like ver. 1 or ver. 2) each time you’re using this pipe somewhere.

@Pipe({  name: 'orderBy' })
export class OrderByPipe implements PipeTransform {
  transform(records: Array<any> = [], args?: any): any {
    /* ... */

See the records = [] default in the transform‘s method parameter?

I try to use this as a general rule of thumb to always prepare the pipe for getting no input initially. Makes a lot of headaches go away 🙂

Leave a Comment