我正在尝试构建一个自定义数据集,它可以将数据显示为卡片,也可以显示更为传统的表/列表/网格。如果我不希望模板是可自定义的,我可以很容易地做到这一点,如这个柱塞所示
这里我有一个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>
我怎么才能从我现在的位置得到我想要的?
发布于 2016-03-24 22:01:49
我能够解决我的问题,如这里所示
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;
https://stackoverflow.com/questions/35614684
复制相似问题