簡體   English   中英

Angular Material 數據表列按日期范圍排序

[英]Angular Material data table column sort by date range

如何根據日期范圍對日期列進行排序? 角材料數據表。 我正在處理一個項目,現在面臨一個問題,即如何使用 filterPredicate 或 mat-table 中的任何其他選項根據日期范圍 fromDate 和 toDate 對列排序數據進行日期排序。

日期列將顯示在日期范圍之間。 請參考屏幕截圖並在此處查看stackblitz中的項目在此處輸入圖片說明

https://stackblitz.com/edit/angular-pkkvbd-cdtxwz-date-range-filter?embed=1&file=app/table-filtering-example.ts

如果我選擇了2019 年 1 月 1日至 2020 年 12 月 31 日,則數據將顯示所有日期之間的結果

TL;DR: https://stackblitz.com/edit/angular-pkkvbd-cdtxwz-date-range-filter-jzlwxr?file=app/table-filtering-example.ts

您不僅要排序,還要過濾表格。 考慮到您使用的是有角材料,這些是有角材料中的獨立關注點。 您必須首先提供過濾組件並使用該數據手動實現 filterPredicate 函數,是的,手動。

過濾:

export class TableFilteringExample {
  displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
  dataSource = new MatTableDataSource(ELEMENT_DATA);

  applyFilter(filterValue: string) {
    this.dataSource.filterPredicate = filterPeriod;
  }

  filterPeriod(data: T, filter: string) {
    return data.referenceDate > startDateFilter.value() && data.referenceDate < endDateFilter.value();
  }
}

排序功能也可用於您的 material.table 組件,但該組件是為您開箱即用的。 關於如何正確使用 MatSort 組件,請參考https://material.angular.io/components/table/overview#sorting

<table mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8">
...

然后,在您的.ts組件中,您將把 matSort 稱為:

    @ViewChild(MatSort, {static: true}) sort: MatSort;

如果您想完成故事和閱讀文章以了解如何根據您的案例調整材料組件,您需要完成幾個步驟。 我建議你從這里開始你的旅程https://material.angular.io/components/table/overview#sorting

為了達到您預期的結果,您需要更改dataSource類型。 您還需要一種方法來根據用戶的日期范圍選擇重建您的項目數組。

你的xxx.component.ts應該是這樣的。

import { Component } from '@angular/core';
import { MatTableDataSource } from '@angular/material';
import { DatePipe } from '@angular/common';
import {FormControl, FormGroup} from '@angular/forms';
import * as moment from 'moment';

export interface PeriodicElement {
  name: string;
  position: number;
  weight: number;
  DOB: Date;
  created: Date;
}

const ELEMENT_DATA: PeriodicElement[] = [
  { position: 1, name: 'Hydrogen', weight: 1.0079, DOB: new Date(2016, 11, 24), created: new Date(2015, 15, 24) },
  { position: 2, name: 'Helium', weight: 4.0026, DOB: new Date(2018, 18, 24), created: new Date(2018, 11, 24) },
  { position: 3, name: 'Lithium', weight: 6.941, DOB: new Date(1993, 6, 12), created: new Date(1999, 12, 15) },
  { position: 4, name: 'Beryllium', weight: 9.0122, DOB: new Date(2001, 7, 6), created: new Date(2011, 10, 6) },
  { position: 5, name: 'Boron', weight: 10.811, DOB: new Date(2020, 5, 9), created: new Date(2020, 5, 9) },
  { position: 6, name: 'Carbon', weight: 12.0107, DOB: new Date(2008, 7, 14), created: new Date(2008, 7, 14) },
  { position: 7, name: 'Nitrogen', weight: 14.0067, DOB: new Date(1998, 11, 18), created: new Date(1998, 11, 18) },
  { position: 8, name: 'Oxygen', weight: 15.9994, DOB: new Date(2002, 2, 24), created: new Date(2002, 2, 24) },
  { position: 9, name: 'Fluorine', weight: 18.9984, DOB: new Date(2006, 4, 29), created: new Date(2006, 4, 29) },
  { position: 10, name: 'Neon', weight: 20.1797, DOB: new Date(2040, 5, 30), created: new Date(2040, 5, 30) },
];

/**
 * @title Table with filtering
 */
@Component({
  selector: 'table-filtering-example',
  styleUrls: ['table-filtering-example.css'],
  templateUrl: 'table-filtering-example.html',
})
export class TableFilteringExample {
  displayedColumns: string[] = ['position', 'name', 'weight', 'DOB', 'founded'];
  dataSource = ELEMENT_DATA;
  pipe: DatePipe;

filterForm = new FormGroup({
    fromDate: new FormControl(),
    toDate: new FormControl(),
});

get fromDate() { return this.filterForm.get('fromDate'); }
get toDate() { return this.filterForm.get('toDate'); }

  constructor() {
  }

  getDateRange(value) {
    // getting date from calendar
    const fromDate = value.fromDate
    const toDate = value.toDate
    const tempData = <any>this.dataSource;
    let selectedItems: PeriodicElement[] = [];
    if(fromDate !== '' && toDate !== '') {
              tempData.forEach((item, index) => {
            if (item.DOB >= fromDate && item.DOB <= toDate) {
                selectedItems.push(item);
            }
        });

        this.dataSource = selectedItems;
    }
  }


  applyFilter(filterValue: string) {
    // this.dataSource.filter = filterValue.trim().toLowerCase();
  }
}

您可以使用過濾功能。

getDateRange(value) {
    this.dataSource.data = ELEMENT_DATA;
    const fromDate = value.fromDate
    const toDate = value.toDate
    this.dataSource.data = this.dataSource.data.filter(e=>e.DOB > fromDate && e.DOB < toDate ) ;
  }

filter() 方法創建一個新數組,其中包含通過所提供函數實現的測試的所有元素。

有關過濾器功能的更多信息

基於您的示例的 Stackblitz 示例。

如果您想應用自定義行為進行過濾和排序,那么您可以應用以下內容:

自定義過濾示例(在您的構造函數中):

this.dataSourceUPs.filterPredicate = (data: UPs, filter: string) => {
  filter = filter.trim().toLowerCase();
  return this.contains(data.nombreUP, filter) || this.contains(data.ciudad, filter) || this.contains(Number(data.fechaInicio.split("T")[0].split("-")[2]), filter);
}

自定義排序示例:

compare(a: number | string, b: number | string, isAsc: boolean) {
    return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}
sortDataUPs(sort: Sort) {
    const data = this.dataSourceUPs.data.slice();
    if (!sort.active || sort.direction === '') {
      this.dataSourceUPs.data = data;
      return;
    }

    this.dataSourceUPs.data = data.sort((a, b) => {
      const isAsc = sort.direction === 'asc';
      switch (sort.active) {
        case 'periodo': return this.compare(a.periodo, b.periodo, isAsc);
        case 'nombreUP': return this.compare(a.nombreUP, b.nombreUP, isAsc);
        case 'ciudad': return this.compare(a.ciudad, b.ciudad, isAsc);
        case 'programa': return this.compare(a.nombreEdicion + '-' + a.nombrePrograma, b.nombreEdicion + '-' + b.nombrePrograma, isAsc);
        default: return 0;
      }
    });
  }

案例是您放入 html ng-container 中的 matColumnDef 的值,即您放入 displayColumns 數組的列名。 剩下要做的就是像這樣對你的表應用綁定:

<table mat-table [dataSource]="dataSourceUPs" class="mat-elevation-z8" style="width: 100%;" matSort (matSortChange)="sortDataUPs($event)">

您可以注意到案例“programa”是自定義的。 您很可能需要進行正確的導入語句,例如對於 Sort 類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM