我试图使用ng-content来选择性地显示特定区域的某些组件,但我没有让过滤正常工作。
我有一个布局组件,它包含某些组件,这些组件在需要呈现的地方被标记为指令。
<standard-layout class="blah">
<sample-navigation *navBarItem></sample-navigation>
<sample-navigation *navBarItem></sample-navigation>
<sample-form-1 *contentItem></sample-form-1>
<sample-form-2 *contentItem></sample-form-2>
<sample-form-3 *contentItem></sample-form-3>
<sample-navigation *actionBarItem></sample-navigation>
<sample-navigation *actionBarItem></sample-navigation>
</standard-layout>这是我的contentItem指令:
@Directive(selector: '[contentItem]')
class ContentItemDirective implements AfterContentInit {
final ViewContainerRef vcRef;
final TemplateRef template;
final ComponentResolver componentResolver;
ContentItemDirective(this.vcRef, this.template, this.componentResolver);
ComponentRef componentRef;
@override
ngAfterContentInit() async {
final componentFactory =
await componentResolver.resolveComponent(ContentItem);
componentRef = vcRef.createComponent(componentFactory);
(componentRef.instance as ContentItem)
..template = template;
}
}这就是我的ContentItem的样子
@Component(
selector: "content-item",
host: const {
'[class.content-item]': true,
},
template: """
<template [ngTemplateOutlet]="template"></template>
""",
directives: const [NgTemplateOutlet]
)
class ContentItem {
TemplateRef template;
}在standard-layout的模板中,当我执行<ng-content select=""></ng-content>时,它会按预期显示所有组件。
当我尝试过滤组件时,它似乎不起作用:
CSS筛选不显示任何内容:
<ng-content select=".content-item"></ng-content>对content-item标记本身的筛选也不会显示任何内容:
<ng-content select="[content-item]"></ng-content>我尝试过许多select=...的排列,但似乎无法让它工作。有什么想法吗?
我在角飞镖3.0.0包裹上。
发布于 2017-05-20 14:06:48
设法使它使用@ContentChildren工作
在我的StandardLayout组件中,我使用以下方法过滤输入:
@ContentChildren(ContentItemDirective)
QueryList<ContentItemDirective> contentItems;
@ContentChildren(ActionBarItemDirective)
QueryList<ActionBarItemDirective> actionBarItems;
@ContentChildren(NavBarItemDirective)
QueryList<NavBarItemDirective> navBarItems;现在在standard-layout模板中,可以循环遍历项目并使用ngTemplateOutlet显示模板。
<nav class="nav1" #nav1>
<div *ngFor="let item of navBarItems">
<template [ngTemplateOutlet]="item.template"></template>
</div>
</nav>
<div class="content" #content>
<div *ngFor="let item of contentItems">
<template [ngTemplateOutlet]="item.template"></template>
</div>
</div>
<nav class="nav2" #nav2>
<div *ngFor="let item of actionBarItems">
<template [ngTemplateOutlet]="item.template"></template>
</div>
</nav>https://stackoverflow.com/questions/44085848
复制相似问题