我正在尝试构建一个自定义数据网格,可以将数据显示为卡片或更传统的表格/列表/网格。如果我不希望模板可以自定义,我可以很容易地完成它,如plunker
所示这里我有一个my-grid
组件,它传递了要呈现的数据。然后我循环遍历数据并呈现card-view
或list-view
组件,具体取决于由view toggle
(app/my-grid.ts
文件中的代码)控制的所需视图
我想提供传递自定义模板的功能,我想的是这样的:
<my-grid>
<card-view-template>
<template var-item>
<h4>{{item.name}}</h4>
{{item.home}}
</template>
</card-view-template>
<list-view-template>
<template var-item>
<span>{{item.name}}</span>
{{item.home}}
</template>
</card-view-template>
</my-grid>
我怎样才能从我所处的位置找到我想要的东西?
答案 0 :(得分:4)
我能够解决我的问题,如here
所示import {Component, Directive, ContentChild, TemplateRef} from 'angular2/core';
@Directive({
selector: 'card-view'
})
export class CardViewComponent {
@ContentChild(TemplateRef) itemTmpl;
ngAfterContentInit() {
console.log('In CCV', this.itemTmpl)
}
}
希望它可以帮助其他任何面临类似问题的人。或者也许有人可以指出我更好的解决方案
更新:
对于较新版本的ng2(RC在编写本文时),在某些情况下需要使用forwardRef()
,如下所示:
@ContentChild(forwardRef(() => CardViewComponent)) cardViewComponent;
@ContentChild(forwardRef(() => ListViewComponent)) listViewComponent;