微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript-Angular 2中的嵌套模板

这个问题已经在这里有了答案:            >            Passing Components in Angular2                                    1个
我有一个组件,< DropDown>< / DropDown>并且我想让用户传递DropDown中列表项的模板.

假设他们想创建一个包含图像和文本的自定义列表项,他们将执行以下操作:

<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中.

是否有可能做到这一点?

解决方法:

您可以尝试以下解决方案:

@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相同的功能

另请参阅相关问题:

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐