我的应用程序中有许多模块,在每个模块中我需要有一个包含所有元素的列表。该列表看起来很孤独并执行相同的功能,我想在一个单独的组件中呈现它,但我遇到了一个问题,每个模块中的元素都有不同的字段。例如
class Person {
id: number;
name: string;
...
}
class Address {
id: number;
street: string
...
}
对于我想要列表组件显示名称列表的人。对于地址,我希望列表组件显示地址列表 创建通用列表的最佳方法是什么?
实施例
导航list.component.ts
@Component({
selector: 'navigation-list',
templateUrl: './navigation-list.component.html',
styleUrls: ['./navigation-list.component.scss']
})
export class NavigationListComponent {
public searchString: string;
@Input() navigationListItems: Array<NavigationListItem>;
@Output() deletedElementId = new EventEmitter();
public onDelete(id: number) {
this.deletedElementId.emit(id);
}
}
导航list.component.html
<md-input-container>
<input mdInput placeholder="Search" [(ngModel)]="searchString">
</md-input-container>
<md-nav-list dense>
<md-list-item>
<button md-line md-raised-button routerLink="./">Create</button>
</md-list-item>
<md-list-item *ngFor="let listItem of ( navigationListItems | filterByName: searchString )">
<a md-line routerLink={{listItem.id}}>{{ listItem.title }}</a>
<button
md-icon-button
color="warn"
(click)="onDelete(listItem.id)"
>
<i class="mkv-icon-navigation icon-remove"></i>
</button>
</md-list-item>
</md-nav-list>
答案 0 :(得分:0)
您可以创建单个类,然后将对象转换为您创建的通用类。然后在HTML中使用该对象。
class Person {
id: number;
name: string;
...
}
class Address {
id: number;
street: string
...
}
class UniversalClass {
key: number,
value: string
}
private CastObject(item: Address): UniversalClass {
return new UniversalClass({
key: item.id,
value: item.street
});
}