2016-09-18 147 views
1

我有一個組件<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。

可以做到這一點嗎?

+0

我認爲這是你所追求的:https://toddmotto.com/transclusion-in-angular-2-with-ng-content。 ng-content標籤。 – Avi

+0

你能發佈更多的代碼嗎?你使用ngFor? – yurzui

+0

我更新了代碼,我在li中使用ngFor來查看數據。 @Avi我不能使用ng-content,因爲它在ngFor循環中不起作用。 ng內容只會顯示一次,而不是每個li元素。這就是爲什麼我必須使用模板方法 – Sunny

回答

3

你可以嘗試以下解決方案:

@Component({ 
    selector: 'DropDownList', 
    template: ` 
    <li *ngFor="let item of items" (click)="handleOnSelect(item)"> 
    <template [ngTemplateOutlet]="itemWrapper" [ngOutletContext]="{ $implicit: item }"> 
    </template> 
    </li>` 
}) 
export class DropDownListComponent { 
    @Input() itemWrapper: TemplateRef<any>; 
    @Input() items: any; 
    handleOnSelect(item) { 
    console.log('clicked'); 
    } 
} 

@Component({ 
    selector: 'DropDown', 
    template: ` 
    <div> 
     <ul> 
      <DropDownList [items]="items" [itemWrapper]="itemWrapper"> 
      </DropDownList> 
     </ul> 
    </div>` 
}) 
export class DropDownComponent { 
    @Input() items: string[]; 
    @ContentChild(TemplateRef) itemWrapper: TemplateRef<any>; 
} 

@Component({ 
    selector: 'my-app', 
    template: ` 
    <DropDown [items]="items"> 
     <template let-item> 
      <h1>item: {{item}}</h1> 
     </template> 
    </DropDown> 
    ` 
}) 
export class App { 
    items = ['this','is','a','test']; 
} 

Plunker Example

ngTemplateOutlet(^ 2.0.0-rc.2)指令具有相同的功能自定義指令NgWrapper

另請參閱相關問題:

+0

這是完美的!非常感謝! – Sunny