Reputation: 7856
How Can i reverse without changing positions of elements in an array, should just update the view with a pipe
I can use array.reverse()
but that places the first item at the last and so on so elements index changes
Here is stackblitz code which I am stuck at
import { Component } from '@angular/core';
export interface Order {
value: string;
viewValue: string;
}
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'orderBy'
})
export class OrderByPipe implements PipeTransform {
transform(value: any[], arg: string): any {
console.log('value', value);
console.log('args', arg);
if (arg === 'desc') {
return value.reverse();
}
if (arg === 'asc') {
return value;
}
}
}
/**
* @title Basic select
*/
@Component({
selector: 'select-overview-example',
template: `<h4>Basic mat-select</h4>
<mat-form-field>
<mat-label>Sort Order</mat-label>
<mat-select value='asc'>
<mat-option *ngFor="let order of orders" (click)="changeOrder(order.value)" [value]="order.value">
{{order.viewValue}}
</mat-option>
</mat-select>
</mat-form-field>
<ul>
<li *ngFor="let item of items| orderBy : sort; index as i">{{i}} -> {{item}}</li>
</ul>`,
styleUrls: ['select-overview-example.css'],
})
export class SelectOverviewExample {
orders: Order[] = [
{ value: 'asc', viewValue: 'Ascending' },
{ value: 'desc', viewValue: 'Descending' }
];
items: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
sort: string = 'asc';
changeOrder(val: string) {
console.log('val', val);
this.sort = val;
}
}
Upvotes: 2
Views: 5111
Reputation: 2747
Our main problem is to change view only in reverse order. so no need to update logic. only update CSS.
If items are display using flex-box CSS, then we can reverse it by using flex-direction
property.
flex-direction : row;
flex-direction: column;
flex-direction: row-reverse;
flex-direction: column-reverse;
and if items are display using UL and LI, then apply below css for reverse Order. like below :
ul {
-moz-transform: rotate(180deg);
-webkit-transform: rotate(180deg);
transform: rotate(180deg);
}
ul > li {
-moz-transform: rotate(-180deg);
-webkit-transform: rotate(-180deg);
transform: rotate(-180deg);
}
Upvotes: 4
Reputation: 12613
You can clone your array using let clone = myArray.slice();
. Reordering the clone will not impact the original array. It looks like that's what Material's table does.
Upvotes: 0
Reputation: 44
You can make a custom pipe for sorting asc or desc and sort your array
##TEMPLATE##
<div *ngFor="let order of Orders | orderBy:'asc'">
##PIPE##
export class OrderByPipe implements PipeTransform {
transform(orders: any[], field: string): any[] {
orders.sort((a: any, b: any) => {
if (a[field] < b[field]) {
return -1;
} else if (a[field] > b[field]) {
return 1;
} else {
return 0;
}
});
}
}
Upvotes: 0