【发布时间】:2017-12-09 18:21:24
【问题描述】:
我正在使用 Angular 创建选项卡控件。结果应如下所示:
<tabs>
<tab header="tab 1">
hello
</tab>
<tab header="tab 2">
world
</tab>
</tabs>
现在,tab 组件看起来像这样:
@Component({
selector: 'tab',
template: `<ng-content></ng-content>`
})
export class TabComponent {
@Input() header: string;
}
tabs 组件看起来像这样:
@Component({
selector: 'tabs',
template: `
<div class="tabs">
<ul>
<li *ngFor="let tab of tabs">
<a (click)="selectTab(tab)">
{{tab.header}}
</a>
</li>
</ul>
</div>
`,
})
export class TabsComponent {
@ContentChildren(TabComponent) tabs;
selectTab(tab: TabComponent) {
}
}
现在,当调用 selectTab() 方法时,我希望将按下的选项卡(“hello”或“world”)的内容呈现在模板的底部。
TabsComponent中基本上需要有某种选项卡占位符,并且需要绑定到当前选中的TabComponent。
无论如何,我无法让它工作。我尝试过使用 ng-template 和 createEmbeddedView,但我不明白如何从组件中获取 TemplateRef,而且我不完全确定这是正确的路要走。
先谢谢了!
【问题讨论】:
-
为什么
TabsComponent模板中没有ng-content? -
因为那时所有的标签都会出现在那里,而我只希望出现 selected 标签。
-
如果你不使用它,Angular 会忽略
<tabs>content ignored</tabs>标签内的所有内容。 -
这不准确,因为我使用的是 ContentChildren 装饰器。它检索选项卡内的所有 TabComponent,然后由 TabsComponnet 使用以生成选项卡标题。当用户按下选项卡标题时,我想显示相关的 TabComponent。
-
对,您可以通过
ContentChildren访问它们。tabcompoennt内容到底需要什么?现在它只是文本,你需要那个文本吗?你能添加这样的模板引用吗<tab><span #t> hello</span></tab>
标签: javascript angular typescript