[英]angular pass component to component as parameter
我嘗試建立一個可重用的列表,該列表顯示T類型的元素。這些元素的視圖取決於T。為了打破這種依賴性,我決定也傳遞視圖組件。
例如,該列表包含類型為“汽車”的元素。 傳遞到此列表的視圖用於顯示每個元素的屬性“ .ps”和“ .color”。
可悲的是,我是Angular的新手,我不知道該怎么做。 我想做這樣的事情:
仿制list.ts
export class GenericListComponent<T> {
@Input() readonly elements: T[]; // Array of objects to be listed;
@Input() embeddedComponentAsViewForEachGivenElementOfTypeT: any;
...
}
仿制list.html
<mat-list>
<mat-list-item *ngFor="let el of elements">
<embeddedComponentAsViewForEachGivenElementOfTypeT [element]=el </embeddedComponentAsViewForEachGivenElementOfTypeT>
</mat-list-item>
</mat-list>
使用列表如下所示:
<app-generic-list [elements]="ArrayOfComplexObjects"
[embeddedComponentAsViewForEachGivenElementOfTypeT]="ViewComponentToDisplayComplexObject"> </app-generic-list>
有任何想法嗎 ? 謝謝 :)
----更新:
我采用Brandons的答案,但是通過使用* ngSwitchCase並添加了工廠組件來稍微改變了實現。 這種方法的壞處是,每次有新的ListElement出現時,都必須修改工廠組件(違反“ Open-Close-Principle”。另一方面,此依賴關系保留在一個工廠中。
這是代碼:
通用列表,HTML
<mat-list>
<mat-list-item *ngFor="let el of elements">
<app-factory-listelement elementToDisplay="el" typeOfListElement="carListElement"> </app-factory-listelement>
</mat-list-item>
</mat-list>
工廠listelement.ts
export class FactoryListelementComponent implements OnInit {
@Input() typeOfListElement: string;
@Input() elementToDisplay: any;
carType = 'carListElement';
bikeType = 'bikeListElement';
...
工廠listelement.html
<div [ngSwitch]="typeOfListElement">
<app-car-info-list-element TheCarElement="elementToDisplay" *ngSwitchCase="carType" >...</app-car-info-list-element>
<app-bike-info-list-element TheBikeElement="elementToDisplay" *ngSwitchCase="bikeType" >...</app-bike-info-list-element>
<!--default case when there are no matches -->
<div *ngSwitchDefault> ERROR ! Make some error.log or so</div
</div>
我認為那是不可能的。 與元素屬性一樣,用於引用“ embeddedComponent ...”的HTML元素不是數據綁定對象。 您可以做的是在列表中添加數量有限的子組件,並傳遞一個類似type
in的參數,這將指示該組件使用可用的子組件之一。
因此,在generic-list.html中,您將具有以下內容:
<mat-list>
<mat-list-item *ngFor="let el of elements">
<component-option-one
*ngIf="type === 'componentOptionOne'"
></component-option-one>
<component-option-two
*ngIf="type === 'componentOptionTwo'"
></component-option-two>
<component-option-three
*ngIf="type === 'componentOptionThree'"
></component-option-three>
</mat-list-item>
</mat-list>
您可以使用以下方法創建它:
<app-generic-list
[elements]="arrayOfElements"
[type]="'componentOptionOne'"
></app-generic-list>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.