简体   繁体   中英

How to use ng-content with an ng-container?

I am not getting my components to display when they are within an 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. 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.

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):

@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 . How can I get this working using this ngFor and ngIf ?

You can use ngProjectAs in your MainNav template.

@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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM