如何根据排序更改或更改箭头?

时间:2018-02-07 10:44:42

标签: html css angular typescript

我需要根据排序更改箭头,例如here

sortingPipe.ts:

import { SprBitType } from '../spr-bit-type/sprBitType'; 
import { Pipe, PipeTransform } from '@angular/core'; 

@Pipe({
  name: 'sortingSprBitType'
})

export class SortingSprBitTypePipe implements PipeTransform {
  transform(sprBitTypes: SprBitType[], path: string[], order: number = 1): SprBitType[] {
    // Check if is not null
    if (!sprBitTypes || !path || !order) return sprBitTypes;
    return sprBitTypes.sort((a: SprBitType, b: SprBitType) => {
      // We go for each property followed by path
      path.forEach(property => {
        a = a[property];
        b = b[property];
      })
      // Order * (-1): We change our order
      return a > b ? order : order * (- 1);
    })
  }
}

sortingPipe.spec.ts:

import { TestBed, async } from '@angular/core/testing';
import { SortingSprBitTypePipe } from './sortingSprBitType.pipe';

describe('SortingSprBitTypePipe', () => {
  it('create an instance', () => {
    const pipe = new SortingSprBitTypePipe();
    expect(pipe).toBeTruthy();
  });
});

Component.ts:

...
  path: string[] = ['sprBitType'];
  order: number = 1; // 1 asc, -1 desc;

...

  sortTable(prop: string) {
    this.path = prop.split('.')
    this.order = this.order * (-1); // change order
    return false; // do not reload
  }

...

以下是如何更正确地重新制作html(使用这些符号来排序▲▼):

<a class="sorting" (click)="sortTable('name')" >Name⬍</a>
<a class="sorting" (click)="sortTable('rn')"> RN⬍</a>

1 个答案:

答案 0 :(得分:0)

我能想到的一种方法是使用依赖于*ngIF const的order

所以你的HTML看起来像这样

<a class="sorting" (click)="sortTable('name')" >
    Name
    <label *ngIf="orderByName === 1">▲</label>
    <label *ngIf="orderByName === -1">▼</label>
</a>
<a class="sorting" (click)="sortTable('rn')"> 
    RN
    <label *ngIf="orderByRn === 1">▲</label>
    <label *ngIf="orderByRn === -1">▼</label>
</a>

在你的Component.ts文件中有这个

...

path: string[] = ['sprBitType'];
order: number = 1; // 1 asc, -1 desc;
orderByName: 1; // Guessing that asc is default
orderByRn: 1 // Guessing that asc is default

...

sortTable(prop: string) {
    this.path = prop.split('.')
    this.order = this.order * (-1); // change order
    if(prop == name){
        this.orderByName = this.order;
    }
    if(prop == rn){
        this,orderByName = this.order;
    }
    return false; // do not reload
}