gpt4 book ai didi

angular - 重用自定义指令在 Angular Bootstrap 中制作可排序表

转载 作者:行者123 更新时间:2023-12-05 03:44:21 26 4
gpt4 key购买 nike

我在我的项目中使用 Angular Bootstrap。我在链接 ( https://ng-bootstrap.github.io/#/components/table/examples ) 之后创建了一个表。此表具有可排序和可搜索的功能。按照链接 ( https://stackblitz.com/run?file=app/table-complete.ts ) 中的示例,我在我的项目中创建了一个表。此示例具有用于对表进行排序的自定义指令。代码如下:

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 ) 以使该字段可排序。该行是:

export type SortColumn = keyof IncomeHeadListModel | '';

现在我想对另一个表重用相同的指令。该表使用另一个模型: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});
}
}

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

关于angular - 重用自定义指令在 Angular Bootstrap 中制作可排序表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66478836/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com