Reputation: 1533
I am using a sort method for some data and as I understand, the sort is "activated" before the actual data comes in and although it works, it leaves some error in the console: ERROR TypeError: Cannot read property 'sort' of null.
<ng-container *ngFor="let attendee of (listOfAttendees$ | async | sort:'lastName': 'firstName':'asc')">
<div class="attendees-list__item d-flex">
<div class="attendees-list__item-name course-details-attendees col-4 col-md-4 text text-cooler-grey align-self-center pl-3">
{{ attendee?.lastName }}, {{ attendee?.firstName }}
</div>
</div>
</ng-container>
Is there any good place where I can move the sort function so it does not give the null
output?
Upvotes: 0
Views: 1281
Reputation: 6488
I suggest to edit the observable so that you do not have to sort inside the template
@Component({...})
export class MyComponent {
listOfAttendees$: Observable<Attendant[]>;
sortedAttendees$ = this.listOfAttendees$.pipe(
map(attendees => attendees ? attendees.sort((a, b) => {
const lastname = a.lastName.localeCompare(b.lastName);
return lastname === 0 ? a.firstName.localeCompare(b.firstName) : lastname;
}) : null)
)
}
and in your template
<ng-container *ngFor="let attendee of sortedAttendees$ | async">
Upvotes: 1
Reputation: 21
Can you edit the observable? If so you could emit an empty array instead of a null value. That should prevent the TypeError.
Upvotes: 0