角度5 ngx数据表排序不起作用

时间:2018-03-06 08:26:44

标签: angular typescript ngx-datatable

我正在使用tail来显示数据库中的一些数据。所以为此我已经制作了我的组件(这里我使用酒店作为组件)。 所有酒店都在数据表中显示良好,但酒店名称的排序根本不起作用。当我点击酒店名称标题时,它将表格显示为空白。

我从here

中取了示例

所以现在hotel.component.ts看起来像这样

v-on:change="selectCamera"

hotel.component.html看起来像这样

[ngx-datatable]

和hotel.service.ts看起来像这样

    import { Component, OnInit } from '@angular/core';
    import { HotelService } from '../hotel.service';
    import { HttpClient } from '@angular/common/http';
    import { Hotel } from './hotel';
    import { Router} from '@angular/router';
    import { ViewEncapsulation } from '@angular/core';


@Component({
  selector: 'app-hotel',
  templateUrl: './hotel.component.html',
  styleUrls: ['./hotel.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class HotelComponent implements OnInit {

  hotels: Hotel[] = [];
  loading: boolean = false;
  rows = [];

  columns = [
    { name: 'hotelname', sortable: true },
    { name: 'Action', sortable: false },
  ];

  constructor( 
    public hotelService: HotelService,
    private router: Router
  ) { }

  ngOnInit() {
    this.getAll();
  }

  getAll() {
    this.hotelService.getHotels().subscribe(res => {
      this.rows = res as Hotel[];
    }, err => {
      console.log(err);
    });
  }


  onSort(event) {
    // event was triggered, start sort sequence
    this.loading = true;
    setTimeout(() => {
      const rows = [this.rows];
      console.log(rows);
      // this is only for demo purposes, normally
      // your server would return the result for
      // you and you would just set the rows prop
      const sort = event.sorts[0];
      rows.sort((a, b) => {
        return a[sort.prop].localeCompare(b[sort.prop]) * (sort.dir === 'desc' ? -1 : 1);
      });

      this.rows = rows;
      this.loading = false;
    }, 1000);
  }

}

1 个答案:

答案 0 :(得分:1)

const rows = [this.rows];将生成一个数组数组,在设置为this.rows时将产生一个空网格。将该行更改为

const rows = [...this.rows];

这会将this.rows的每个元素复制到新的数组行,并且可以进行排序