重用自定义指令使 sortable table in Angular Bootstrap

Reuse custom directive to make sortable table in Angular Bootstrap

我在我的项目中使用 Angular Bootstrap。我在 link (https://ng-bootstrap.github.io/#/components/table/examples). This table has sortable and searchable features. Following the example from link (https://stackblitz.com/run?file=app/table-complete.ts) 之后创建了一个 table 我在我的项目中创建了一个 table。此示例具有用于对 table 进行排序的自定义指令。代码如下:

import { Directive, EventEmitter, Input, Output } from "@angular/core";
import { IncomeHeadListModel } from "../_models/income-head-list.model";

export type SortColumn = keyof IncomeHeadListModel | '';
export type SortDirection = 'asc' | 'desc' | '';
const rotate: {[key: string]: SortDirection} = { 'asc': 'desc', 'desc': '', '': 'asc' };

export interface SortEvent {
  column: SortColumn;
  direction: SortDirection;
}

@Directive({
  selector: 'th[sortable]',
  host: {
    '[class.asc]': 'direction === "asc"',
    '[class.desc]': 'direction === "desc"',
    '(click)': 'rotate()'
  }
})
export class NgbdSortableHeader {

  @Input() sortable: SortColumn = '';
  @Input() direction: SortDirection = '';
  @Output() sort = new EventEmitter<SortEvent>();

  rotate() {
    this.direction = rotate[this.direction];
    this.sort.emit({column: this.sortable, direction: this.direction});
  }
}

在这个指令中,我必须传递一个模型 (IncomeHeadListModel ) 来使字段 sortable。该行是:

export type SortColumn = keyof IncomeHeadListModel | '';

现在我想为另一个 table 重用相同的指令。 table 使用另一个模型,即:ExpenseHeadListModel。我怎样才能在下面的行中传递另一个模型:

export type SortColumn = keyof IncomeHeadListModel | '';

简单的解决方案是简化输入并只使用字符串作为列名。

import { Directive, EventEmitter, Input, Output } from "@angular/core";
import { IncomeHeadListModel } from "../_models/income-head-list.model";

export type SortDirection = 'asc' | 'desc' | '';
const rotate: {[key: string]: SortDirection} = { 'asc': 'desc', 'desc': '', '': 'asc' };

export interface SortEvent {
  column: string;
  direction: SortDirection;
}

@Directive({
  selector: 'th[sortable]',
  host: {
    '[class.asc]': 'direction === "asc"',
    '[class.desc]': 'direction === "desc"',
    '(click)': 'rotate()'
  }
})
export class NgbdSortableHeader {

  @Input() sortable: string = '';
  @Input() direction: SortDirection = '';
  @Output() sort = new EventEmitter<SortEvent>();

  rotate() {
    this.direction = rotate[this.direction];
    this.sort.emit({column: this.sortable, direction: this.direction});
  }
}

可能有更好的解决方案利用泛型并从父组件或上下文推断类型。或者提供类型作为输入 属性。我不确定这是否可能。