Get Off My Lawn
Get Off My Lawn

Reputation: 36311

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?

Upvotes: 2

Views: 2682

Answers (1)

Vladimir Bogomolov
Vladimir Bogomolov

Reputation: 1794

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.

Upvotes: 4

Related Questions