Angular 2中的嵌套模板 [英] Nested Templates in Angular 2

查看:118
本文介绍了Angular 2中的嵌套模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组件,< DropDown>< / DropDown> ,我想让用户传入DropDown中列表项的模板。

I have a component, <DropDown></DropDown> and I want to let the user pass in a template for the list items in the DropDown.

假设他们想制作一个包含图片和文字的自定义列表项,他们会这样做:

Assuming they want to make a custom list item that has an image and text they would do something like this:

<DropDown [data]="myData">
    <template>
        <span> <img src="..."> Some Text <span>
    </template>
</DropDown>

在我的 DropDown 组件的HTML中我拥有:

Inside the HTML of my DropDown component I have:

<div>
    <ul>
        <DropDownList [data]="data">
        </DropDownList>
    </ul>
</div>

在DropDownList组件中,我有以下HTML:

In the DropDownList component I have the following HTML:

<li *ngFor="let item of data
    (click)="handleOnSelect(item)">
    [class.selected]="selectedItems.includes(item)">

    <template [ngWrapper]="itemWrapper>
    </template>
</li>

(我正在使用此帖子中的模板包装方法:
在Angular 2中使用ngForTemplate时绑定事件

(I am using the template wrapper method from this post: Binding events when using a ngForTemplate in Angular 2)

如果我在DropDown组件的HTML中包含li元素,则此方法有效。但是,我想将li包装到DropDownList组件中,并将用户从DropDown提供的模板传递给DropDownList。

This method works if I have the li elements within the DropDown component's HTML. However, I want to have wrap the li's into a DropDownList component and pass the template the user gave from DropDown into DropDownList.

是否可以这样做?

推荐答案

你可以试试以下解决方案:

You could try the following solution:

@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示例

Plunker Example

ngTemplateOutlet (^ 2.0.0-rc.2)指令具有与你的自定义指令 NgWrapper

The ngTemplateOutlet(^2.0.0-rc.2) directive has the same functionality as your custom directive NgWrapper

参见相关问题:

  • Creating a dynamic repeater with ng-content transclusion with Angular2
  • Switch html templates dynamically during runtime on user action in angular 2

这篇关于Angular 2中的嵌套模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆