问题
I made the following structure in my json file with Firebase Real Time Database to work on Composer and his Compositions:
I have the following service that give me the data of one composer with his composition
getComposerWithKey(key: string): Observable<Composer> {
const memberPath = `composer/${key}`;
this.composer = this.db.object(memberPath)
.snapshotChanges().map(action => {
const $key = action.payload.key;
const arrcompositions = action.payload.val().compositions?Object.entries(action.payload.val().compositions):null;
const data = {
$key,
arrcompositions,
...action.payload.val() };
return data;
});
return this.composer
}
Now I can get the composer info with a list of his compositions with the ngFor directive :
<mat-list-item *ngFor="let composition of composer.arrcompositions">
{{ composition[1] }}
</mat-list-item>
My problem is that I can't order the compositions in alphabetic order. I tried to use the ngx-order-pipe but I don't know how to precise the value used to order
<mat-list-item *ngFor="let composition of composer.arrcompositions | orderBy: 'composition[1]'">
{{ composition[1] }}
This obviously doesn't work...
回答1:
You should not use ordering pipes.
The Angular team and many experienced Angular developers strongly recommend moving filtering and sorting logic into the component itself
If you want to sort your items by, let's say, name
, here it goes :
filterBy(prop: string) {
return this.composer.arrcompositions.sort((a, b) => a[prop] > b[prop] ? 1 : a[prop] === b[prop] ? 0 : -1);
}
In your HTML :
<mat-list-item *ngFor="let composition of filterBy('name')">
{{ composition[1] }}
</mat-list-item>
来源:https://stackoverflow.com/questions/48403154/orderby-with-ngfor-array