我有一个对象数组,在这个对象中,我有一些属性,当我单击标题时,我正在对这些属性进行排序,以便在表上显示这些属性.

由于我有多个包含字符串的列、多个包含Numbers的列和多个包含Date的列,我想知道是否有办法在具有数据类型的列上重复使用相同的.Sort代码.

大概是这样的:

<table>
    <tr>
      <th (click)="funcSort('string', 'name')">Name</th>
      <th (click)="funcSort('string', 'food')">Favorite Food</th>
      <th (click)="funcSort('number', 'age')">Age</th>
      <th (click)="funcSort('date', 'birth')">Birth</th>
      <th (click)="funcSort('number', 'carbs')">Carbs</th>
      <th (click)="funcSort('date', 'training')">Training day</th>
    </tr>

    <tr *ngFor="let item of list">
      <td>{{item.name}}</td>
      <td>{{item.food}}</td>
      <td>{{item.age}}</td>
      <td>{{item.birth}}</td>
      <td>{{item.carbs}}</td>
      <td>{{item.training}}</td>
    </tr>
  </table>

Typescript :

infos: any = {
    name: 'stack',
    example: 'example..',
    details: [
      {nome: "ingrid", idade: 12, destino: "manaus"},
      {nome: "ester", idade: 22, destino: "coreia"},
      {nome: "sara", idade: 52, destino: "los angeles"},
      {nome: "laura", idade: 32, destino: "peru"},
      {nome: "priscila", idade: 40, destino: "rio de janeiro"},
      {nome: "paula", idade: 39, destino: "londres"},
      {nome: "simone", idade: 42, destino: "bahia"},
      {nome: "leticia", idade: 26, destino: "argentina"},
      {nome: "raissa", idade: 41, destino: "sao paulo"},
      {nome: "ana", idade: 15, destino: "suecia"},
    ]
  };

sortDir: boolean = true;
list: any = []

ngOnInit(): void {

    let convert = Object.values(this.infos);
    this.lista = convert[2]

}


funcSort(type: string, prop: string){

   //prop would be the second property so that when I pass the function in HTML, I specify which
   //property of the object I want to sort

    if(type == 'string'){
      if(this.sortDir == false){
        this.list.sort(( a: any, b: any ) =>
        b.prop.localeCompare(a.prop))
        this.sortDir = true
      }else if(this.sortDir == true){
        this.list.sort(( a: any, b: any ) =>
        a.prop.localeCompare(b.prop))
        this.sortDir = false
      }
      console.log('string type!')
    }
    
    else if(type == 'number'){
        if(this.sortDir == false){
          this.list.sort(( a: any, b: any ) =>
          b.prop- a.prop))
          this.sortDir = true
        }else if(this.sortDir == true){
          this.list.sort(( a: any, b: any ) =>
          a.prop- b.prop))
          this.sortDir = false
        }
        console.log('number type!')
      }

      else if(type == 'date'){
        if(this.sortDir == false){
          this.list.sort(( a: any, b: any ) =>
          new Date(b.prop).valueOf() - new Date(a.prop).valueOf())
          this.sortDir = true
        }else if(this.sortDir == true){
          this.list.sort(( a: any, b: any ) =>
          new Date(b.prop).valueOf() - new Date(a.prop).valueOf())
          this.sortDir = false
        }
         console.log('date type!')
    
     }

  }

此代码不起作用,因为"a.pro.localeCompare(b.pro.localeCompare)"不存在,并且控制台在.prop和b.prop上显示错误. 所以我想知道是否有一种方法可以在Sort方法上使用另一种方法,一种重用一段代码来对相同类型的列进行排序的方法,或者将localeCompare更改为1,-1的方法?我试过了,但没奏效.

推荐答案

当你使用一个字符串来访问一个特定的属性时,我们不能使用test.prop,其中prop是一个字符串的属性名,而是使用test[prop],这将动态地访问该属性!

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule],
  template: `
    <table>
    <tr>
      <th (click)="funcSort('string', 'name')">Name</th>
      <th (click)="funcSort('string', 'food')">Favorite Food</th>
      <th (click)="funcSort('number', 'age')">Age</th>
      <th (click)="funcSort('date', 'birth')">Birth</th>
      <th (click)="funcSort('number', 'carbs')">Carbs</th>
      <th (click)="funcSort('date', 'training')">Training day</th>
    </tr>
    <tr *ngFor="let item of list">
      <td>{{item.name}}</td>
      <td>{{item.food}}</td>
      <td>{{item.age}}</td>
      <td>{{item.birth}}</td>
      <td>{{item.carbs}}</td>
      <td>{{item.training}}</td>
    </tr>
  </table>
  `,
})
export class App {
  infos: any = {
    name: 'stack',
    example: 'example..',
    details: [
      {
        name: 'ingrid',
        age: 12,
        birth: this.randomDate(new Date(2020, 0, 1), new Date(), 0, 24),
        food: 'carrot',
        carbs: 1200,
        training: this.randomDate(new Date(2020, 0, 1), new Date(), 0, 24),
      },
      {
        name: 'ester',
        age: 22,
        birth: this.randomDate(new Date(2020, 0, 1), new Date(), 0, 24),
        food: 'apple',
        carbs: 3456,
        training: this.randomDate(new Date(2020, 0, 1), new Date(), 0, 24),
      },
      {
        name: 'sara',
        age: 52,
        birth: this.randomDate(new Date(2020, 0, 1), new Date(), 0, 24),
        food: 'banana',
        carbs: 756896,
        training: this.randomDate(new Date(2020, 0, 1), new Date(), 0, 24),
      },
      {
        name: 'laura',
        age: 32,
        birth: this.randomDate(new Date(2020, 0, 1), new Date(), 0, 24),
        food: 'potato',
        carbs: 1243,
        training: this.randomDate(new Date(2020, 0, 1), new Date(), 0, 24),
      },
      {
        name: 'priscila',
        age: 40,
        birth: this.randomDate(new Date(2020, 0, 1), new Date(), 0, 24),
        food: 'tomato',
        carbs: 2546,
        training: this.randomDate(new Date(2020, 0, 1), new Date(), 0, 24),
      },
      {
        name: 'paula',
        age: 39,
        birth: this.randomDate(new Date(2020, 0, 1), new Date(), 0, 24),
        food: 'beans',
        carbs: 1234,
        training: this.randomDate(new Date(2020, 0, 1), new Date(), 0, 24),
      },
      {
        name: 'simone',
        age: 42,
        birth: this.randomDate(new Date(2020, 0, 1), new Date(), 0, 24),
        food: 'radish',
        carbs: 345,
        training: this.randomDate(new Date(2020, 0, 1), new Date(), 0, 24),
      },
      {
        name: 'leticia',
        age: 26,
        birth: this.randomDate(new Date(2020, 0, 1), new Date(), 0, 24),
        food: 'fried rice',
        carbs: 12000,
        training: this.randomDate(new Date(2020, 0, 1), new Date(), 0, 24),
      },
      {
        name: 'raissa',
        age: 41,
        birth: this.randomDate(new Date(2020, 0, 1), new Date(), 0, 24),
        food: 'rice',
        carbs: 1500,
        training: this.randomDate(new Date(2020, 0, 1), new Date(), 0, 24),
      },
      {
        name: 'ana',
        age: 15,
        birth: this.randomDate(new Date(2020, 0, 1), new Date(), 0, 24),
        food: 'chapathi',
        carbs: 1300,
        training: this.randomDate(new Date(2020, 0, 1), new Date(), 0, 24),
      },
    ],
  };

  sortDir: boolean = true;
  list: any = [];

  constructor() {}

  ngOnInit(): void {
    let convert = Object.values(this.infos);
    this.list = convert[2];
  }

  funcSort(type: string, prop: string) {
    //prop would be the second property so that when I pass the function in HTML, I specify which
    //property of the object I want to sort

    if (type == 'string') {
      if (!this.sortDir) {
        this.list.sort((a: any, b: any) => b[prop].localeCompare(a[prop]));
        this.sortDir = true;
      } else {
        this.list.sort((a: any, b: any) => a[prop].localeCompare(b[prop]));
        this.sortDir = false;
      }
      console.log('string type!');
    } else if (type == 'number') {
      if (!this.sortDir) {
        this.list.sort((a: any, b: any) => b[prop] - a[prop]);
        this.sortDir = true;
      } else {
        this.list.sort((a: any, b: any) => a[prop] - b[prop]);
        this.sortDir = false;
      }
      console.log('number type!');
    } else if (type == 'date') {
      if (!this.sortDir) {
        this.list.sort(
          (a: any, b: any) =>
            new Date(b[prop]).valueOf() - new Date(a[prop]).valueOf()
        );
        this.sortDir = true;
      } else {
        this.list.sort(
          (a: any, b: any) =>
            new Date(a[prop]).valueOf() - new Date(b[prop]).valueOf()
        );
        this.sortDir = false;
      }
      console.log('date type!');
    }
  }

  randomDate(start: any, end: any, startHour: any, endHour: any) {
    var date = new Date(+start + Math.random() * (end - start));
    var hour = (startHour + Math.random() * (endHour - startHour)) | 0;
    date.setHours(hour);
    return date.toISOString().slice(0, 10);
  }
}

bootstrapApplication(App);

stackblitz

Html相关问答推荐

按钮的字体重量在鼠标悬停时随过渡而变化

如何将数据发送到Flask 应用程序中的表单文本框

springBoot + Thymeleaf:属性中的UTF-8

如何才能完成这个背景按钮

打印pdf时100 vh迪夫有半页高

我能阻止浏览器跨跨区边界折叠空格吗?

如何在所有屏幕大小下使带有背景图像的伪元素作为标题的衬底?

风格规则应该适用于响应图像的哪些方面?哪种规则适用于<;图片和gt;,哪种规则适用于<;img>;?

如何保持嵌套进度条的背景色?

如何在HTML中适当地为单选按钮网格添加标签?

如何将功能附加到嵌入式药剂中的按钮?

Swift WkMessageHandler 消息不发送

带标签 css 的 div 内的中心图标

如何垂直平移一个元素,使其新位置位于另外两个元素之间?

我如何使用 CSS nth-child(odd) nth-child(even) 来对齐 CSS 网格中的列?

是否可以使 huxtable 输出悬停?

如何使用 CSS 制作蜂窝状网格?

圆形边框显示在该部分后面.怎么修?

flex-box 中的图像在 Chrome 和 Firefox 中看起来不同 - 如何使它们在 Firefox 中看起来像?

HTML 标记未在页面上展开