0
我的應用程序中有很多模塊,並且在每個模塊中我需要列出所有元素。該列表看起來很孤獨,並且執行相同的功能,我想將它呈現在一個單獨的組件中,但是我遇到了一個問題,每個模塊中的元素都有不同的字段。例如如何在Angular 2上創建項目的通用列表?
class Person {
id: number;
name: string;
...
}
class Address {
id: number;
street: string
...
}
對於我希望那個list-component顯示名稱列表的人。對於我希望列表組件顯示地址列表的地址 創建通用列表的最佳方式是什麼?
例
導航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>
請詳細說明您嘗試完成的內容。什麼是「通用名單」或「所有要素」?例如,添加一些具體的示例數據和您期望從該數據生成的HTML。通常在Angular中使用'* ngFor'來生成列表。 https://angular.io/guide/template-syntax#expression-context,https://angular.io/api/common/NgForOf –
let list = any []; ?爲什麼不是兩個列表?爲什麼不如果(列表['中的'關鍵'))? – Carsten
如果你問如何創建幾個組件共享相同的方法,但以不同的方式顯示的東西,那麼你可以這樣做:有一個父類ListComponent,其中包含一個數組,以及允許操作數組的常用方法(添加一個項目等),像PersonListComponent這樣的幾個子類繼承ListComponent 。另一種方法是簡單地將組件的複雜方法委派給知道如何處理數組操作的共享類。 –