我有一個組件<DropDown></DropDown>
,我想讓用戶傳遞DropDown中列表項的模板。Angular 2中的嵌套模板
假設他們想使具有圖像和文本,他們會做這樣的事情的自定義列表項:
<DropDown [data]="myData">
<template>
<span> <img src="..."> Some Text <span>
</template>
</DropDown>
我DropDown
組件的HTML裏面我有:
<div>
<ul>
<DropDownList [data]="data">
</DropDownList>
</ul>
</div>
在DropDownList組件中,我使用以下HTML:
<li *ngFor="let item of data
(click)="handleOnSelect(item)">
[class.selected]="selectedItems.includes(item)">
<template [ngWrapper]="itemWrapper>
</template>
</li>
(我正在使用本文中的模板包裝器方法: Binding events when using a ngForTemplate in Angular 2)
如果我在DropDown組件的HTML中具有li元素,此方法可行。但是,我想將li包裝到DropDownList組件中,並將用戶從DropDown提供的模板傳遞給DropDownList。
可以做到這一點嗎?
我認爲這是你所追求的:https://toddmotto.com/transclusion-in-angular-2-with-ng-content。 ng-content標籤。 – Avi
你能發佈更多的代碼嗎?你使用ngFor? – yurzui
我更新了代碼,我在li中使用ngFor來查看數據。 @Avi我不能使用ng-content,因爲它在ngFor循環中不起作用。 ng內容只會顯示一次,而不是每個li元素。這就是爲什麼我必須使用模板方法 – Sunny