[英]How to use ng-content with an ng-container?
I am not getting my components to display when they are within an ng-container
.当我的组件在ng-container
时,我没有显示它们。 I have an array of items that I am looping over where each item has a boolean value of whether or not the user can see the item based on their access.我有一个我正在循环的项目数组,其中每个项目都有一个 boolean 值,即用户是否可以根据他们的访问权限看到该项目。 Since I cannot place two structural directives on an element I decided to use an ng-container
for the ngFor
and then place the ngIf
on the component.由于我不能在一个元素上放置两个结构指令,我决定为ngFor
使用ng-container
,然后将ngIf
放在组件上。
This is the primary side nav component which displays a list of side nav items.这是显示侧导航项目列表的主要侧导航组件。
@Component({
selector: 'side-nav',
template: '<ng-content select="side-nav-item"></ng-content>'
})
export class SideNav { }
This is an example side nav item (for this purpose it does nothing except display an h2):这是一个示例侧导航项(为此,它除了显示 h2 之外什么都不做):
@Component({
selector: 'side-nav-item',
template: '<h2>Side Nav Item</h2>'
})
export class SideNavItem { }
This utilizes the two above components这利用了上述两个组件
@Component({
selector: 'main-nav',
template: `
<side-nav>
<ng-container *ngFor="let item of sideNavItems">
<side-nav-item *ngIf="item.hasAccess"></side-nav-item>
</ng-container>
</side-nav>
<side-nav>
<side-nav-item *ngFor="let item of sideNavItems"></side-nav-item>
</side-nav>
`
})
export class MainNav {
sideNavItems: ISidNavItem[] = [
{
hasAccess: true, uri: '/dashboard'
}
]
}
In this StackBlitz I would like to see two components printed, but I am only getting the last one because it is not inside of an ng-container
.在这个StackBlitz 中,我希望看到打印两个组件,但我只得到最后一个,因为它不在ng-container
内。 How can I get this working using this ngFor
and ngIf
?我怎样才能使用这个ngFor
和ngIf
来完成这个工作?
You can use ngProjectAs
in your MainNav
template.您可以在MainNav
模板中使用ngProjectAs
。
@Component({
selector: 'main-nav',
template: `
<side-nav>
<ng-container *ngFor="let item of sideNavItems" ngProjectAs="side-nav-item">
<side-nav-item *ngIf="item.hasAccess"></side-nav-item>
</ng-container>
</side-nav>
<side-nav>
<side-nav-item *ngFor="let item of sideNavItems"></side-nav-item>
</side-nav>
`
})
export class MainNav {
sideNavItems: ISidNavItem[] = [
{
hasAccess: true, uri: '/dashboard'
}
]
}
This way the select
of the ng-content
will read the ng-container
as a side-nav-item
.这样, ng-content
的select
会将ng-container
读取为side-nav-item
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.