2016-09-18 91 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