kvanberendonck kvanberendonck - 3 years ago 50
Javascript Question

ng-content transclude from parents scope when there are nested components

Using Angular 2/4, I have a complex page template.

Suppose I have 3 mutually nested components:

, inside that
and inside that
with custom selectors set appropriately.

html template:


html template:

<section class="dynamic-content" *ngIf="!collapsed" #dynamicContent>

html template:

<ng-content selector="card-layout-title"></ng-content>

Then, on my actual page template:

<card-layout-title>Title goes here</card-layout-title>

ng-content selector="card-layout-title"
only works when the direct parent is the component with the tag inside to select, i.e. from
I am unable to select 2-levels-up the nested components to find the content to transclude into

How can I do this (preferably without adding and passing a template ref into each level, as there are 5-10 nested components at each level)?

Answer Source

First, it's <ng-content select=".card-layout-title"></ng-content> and not <ng-content selector=".card-layout-title"></ng-content>; easy mistake to make, given the lack of documentation.

It seems, from my testing, that using Transclusion in Angular 2/4 replaces the top-level content first, so that by the time it gets down to the ng-content selector, the .card-layout-title element no longer exists. So, I propose that a solution to this problem be that you "walk" the top-level content down the chain with nested ng-content elements. Plunker

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download