首页 > 解决方案 > 角垫排序。缺少类型

问题描述

[appSort]="dataSource 这里是问题:

“MatTableDataSource”类型缺少“ContactListEntry”类型的以下属性:i

<ng-container matColumnDef="id">
                <th mat-header-cell *matHeaderCellDef [appSort]="dataSource" data-order="desc" data-name="employeeId" mat-sort-header>ID</th>
                <td mat-cell *matCellDef="let formular">{{formular.id}}</td>
            </ng-container>

'''

export class Sort {

  private sortOrder = 1;
  private collator = new Intl.Collator(undefined, {
      numeric: true,
      sensitivity: "base",
  })

  constructor() { }

  public startSort(property, order, type = "") {
      if (order === "desc") {
          this.sortOrder = -1;
      }
      return (a, b) => {
          if (type === "date") {
              return this.sortData(new Date(a[property]), new Date(b[property]));
          } else {
              return this.collator.compare(a[property], b[property]) * this.sortOrder;
          }
      }
  }

  private sortData(a, b) {
      if (a < b) {
          return -1 * this.sortOrder;
      } else if (a > b) {
          return 1 * this.sortOrder;
      } else {
          return 0 * this.sortOrder;
      }
  }
}

'''

import { Directive, Input, Renderer2, ElementRef, HostListener } from '@angular/core';
import { ContactListEntry } from '../contact-list-entry';

import { Sort } from '../data-service';

@Directive({
  selector: '[appSort]'
})
export class SortDirective {


  @Input() appSort: ContactListEntry;

  constructor(private renderer: Renderer2, private targetElement: ElementRef) { }

  @HostListener("click")

  sortData(){


    const sort = new Sort();

    const elem = this.targetElement.nativeElement;

    const order = elem.getAttribute("data-order");

    const type = elem.getAttribute("data-type");

    const property = elem.getAttribute("data-name");


    if(order === "desc"){
      this.appSort.sort(sort.startSort(property, order, type)); // 
      elem.setAttribute("data-order", "asc");
    } else {                                                          // Problem mit quick fix behoben!!!
      this.appSort.sort(sort.startSort(property, order, type)); //
      elem.setAttribute("data-order", "desc");
    }

  }
}

我的问题是 [appSort]="dataSource" 是红色的并且 appSort 不能使用。我希望可以使用 appSort,以便可以执行 appSort 中的函数,或者可以使用 Angular Material Sort 对数组项进行排序。

感谢帮助 :)

标签: angulartypescript

解决方案


在您的指令更改中

@Input() appSort: ContactListEntry;

@Input() appSort: MatTableDataSource<ContactListEntry>;

或在您的模板更改中

[appSort]="dataSource"

至:

[appSort]="dataSource.data"

并保持原样。


推荐阅读