angular: ContentChildren doesn't get children created with NgTemplateOutlet

Original title: ViewChildren doesn’t get children created with NgTemplateOutlet

Please see comments below…

I’m submitting a …

[x] bug report

Current behavior When you use ngTemplateOutlet to render a template passing by input property ViewChildren don’t get or don’t find in the redered elements.

Expected behavior I think ViewChildren should get the elements rendered by ngTemplateOutlet.

Minimal reproduction of the problem with instructions In this plunkr, on app.ts file, you can see a Child component and a Parent component, Parent component has an input property called template1, this accept a TemplateRef that is rendered using ngTemplateOutlet. Parent component has a ViewChildren collection to get the Child components and shows the length of this collection in the end of template.

Well, using this component this way:

    <ng-template #template1>
        <child></child>
        <child></child>
    </ng-template>
    <parent [template1]="template1"></parent>

The Parent component render the two Child components but the length of ViewChildren collection is 0. You can uncomment the line 16 of app.ts file to include a static <child/> component in the Parent template. Then the collection length is 1.

What is the motivation / use case for changing the behavior? It’s would be very useful to pass template to components, rows of grids, lines of lists, … In the other hand I have this plunkr in this case I am rendering Child components using a ngFor, ViewChildren works fine. Since both, ngTemplateOutlet and ngForOf, using viewContainerRef.createEmbeddedView to render the templates … why works with ngFor and not with ngTemplateOutlet? I think that the only reason is that Child components come from different component context, but I would like to know it.

Please tell us about your environment: Windows 10, VisualStudioCode, npm, lite-server

  • Angular version: 4.0.0-rc2

  • Browser: [all]

  • Language: [TypeScript 2.2.1]

About this issue

  • Original URL
  • State: open
  • Created 10 years ago
  • Reactions: 137
  • Comments: 41 (17 by maintainers)

Most upvoted comments

@tolemac I believe that there is some confusion about what @ContentChildren means. In Angular content projection and queries it means “content as it was written in a template” and not “content as visible in the DOM” as you seem to expect.

@pkozlowski-opensource I understand @ContentChildren means in Angular. Is there any way to get the elements projected by a template?

If I have this:

[appComponent]
<ng-template #myTemplate>
  <div>content for other component</div>
</ng-template>
<my-good-component [template]="myTemplate"></my-good-component>

[my-good-component]
<ng-container *ngTemplateOutlet="template"></ng-container>

How to get the template content from my-good-component???

In addition …

[appComponent]
<ng-template #myTemplate let-object>
  <input [(ngModel)]="object.name"/>
  <input [(ngModel)]="object.surname"/>
</ng-template>
<my-generic-person-form [editTemplate]="myTemplate"></my-generic-person-form>

[my-generic-person-form]
<form>
<ng-container *ngTemplateOutlet="editTemplate; context: personObject"></ng-container>
</form>

How is it possible that in version 7 of Angular it is still not possible to make this work? I can not believe it 😄

I have a list of issues that are more than two years open where this is requested or discussed …

@tolemac I believe that there is some confusion about what @ContentChildren means. In Angular content projection and queries it means “content as it was written in a template” and not “content as visible in the DOM” as you seem to expect.

You should think about content nodes as additional input to the component (same as other @Inputs) - a component can use its content to drive its template rendering. As such content is kind of contract between a component author and and a component user. A component author says “hey, if you use me with certain kind of nodes I can make use of them (project, query etc.)”. A component user (meaning: one using a component in a template) must understand the contract and provide (or not) nodes fulfilling a given contract. In other words the component usage place is where a component author and its user agree on the content nodes.

The consequence of this mental model is that Angular only looks at the nodes that are children in a template (and not children in the rendered DOM). To calculate queries and content projection it is enough to inspect a template only without even inserting this content, ex.:

<child></child> <!-- this one doesn't match as not written between parent tags -->
<parent>
   <child></child> <!-- this one DOES match as is written between parent tags -->
</parent>

Your situation is similar, you just happen to have an additional template but the principles are the same:

<ng-template #tplWithChild>
   <child></child> <!-- this one doesn't match as not written between parent tags -->
</ng-template>
<parent>
   <child></child> <!-- this one DOES match as is written between parent tags -->
</parent>

the fact of inserting or not #tplWithChild doesn’t change anything - it is still outside of parent tags!

<ng-template #tplWithChild>
   <child></child> <!-- this one doesn't match as not written between parent tags -->
</ng-template>
<parent>
   <child></child> <!-- this one DOES match as is written between parent tags -->
   <ng-template [ngTemplateOutlet]="tplWithChild"></ng-template> <!-- the act of inserting a template doesn't change anything - it is _definition_ place that counts! -->
</parent>

Having said all this the good news is that I think that you can achieve what you want by moving template to be an actual child:

<parent>
  <ng-template #tplWithChild>
     <child></child> <!-- this one DOES match when this template gets instantiated -->
   </ng-template>
   <child></child> <!-- this one DOES match as is written between parent tags -->
   <ng-template [ngTemplateOutlet]="tplWithChild"></ng-template>
</parent>

Here is a working stackblitz derived from your plunker: https://stackblitz.com/edit/angular-ebgnch?file=src%2Fapp%2Fapp.component.ts

I fully acknowledge that this can be confusing and I would love to make it easier on everyone. Let me know if the proposed solution works for your use-case and if the above explanation makes sense.

I will keep this issue open for a bit to see how we could better model / document this.

Perhaps it isn’t a bug, and it’s so by design.

I have tried to get children included by ngTemplateOutlet by two ways.

  1. Using ViewChildren and TemplateRef Input property rendering childs with ngTemplateOutlet (this issue).
  2. Using ngTemplateOutlet to render to the content and using ContentChildren:
@Component({
    selector: "my-compo",
    template: `
    <parent>
        <ng-container *ngTemplateOutlet="template1"></ng-container>        
    </parent>
    
    `
})
export class MyComponent {
    @Input() template1: TemplateRef
}

@Component({
    selector: "parent",
    template: `
    ...    
    `
})
export class Parent {
    @ContentChildren(Child) children: QueryList<Child>()
    ...
}

And I was searching about that and asking on stackoverflow (Q1 and Q2)

As you can see I’m thinking about this feature since 6 months ago. I think I haven’t written this issue prematurely.

The only way to get it, have been to use native elements.

@Component({ selector: "child", ...})
expor class Child {
    constructor(elem: ElementRef) {
        elem.nativeElement.component = this;
    }
}

@Component({ selector: "parent", ...})
expor class Parent {
    _items = [];
    constructor(private elem: ElementRef) { }
    
    ngDoCheck() {
        const childElements = this.elem.nativeElement.getElementsByTagName("child");
        const childItems = [];
        for (let i = 0; i < childElements.length; i++) {
            childItems.push(childElements[i].component);
        }

        this._items = childItems;
    }
}

If someone knows a better way to do it, I would be very grateful.

Thanks 😉

Any news on that? It could be very helpful to be able to query for stuff projected into components this way.

6 years and we dont have any way, how to query elements from dynamically created things…

I hope it will work AT LEAST with new @defer()…

Since 8 years and 116 votes and this issue hasn’t been answered!

This is not answered because it’s working by design. What we probably need is a new DynamicChild/ren feature to query for things that are view/content at one place but are DOM attached at some other place.

Sad that angular team is working on things noone actually need like format authoring, deprecating class based things… and THIS as absolute core of the framework is dead for 8 years. Just Sad.

Any news on this issue?

As many of you I am also waiting for a potential solution. This is why I created a small workaround which is good enough for me for the moment. I wanted to share this workaround for now. Please note the workaround will only work for WebApplications and won’t work for Ionic / any other native wrapper.

Firstly I created a small service which can hold all the elements which are potential candidates for “contentChildrenExtended()”


export const provideExtendedContendChildrenService = () => {
  return {
    provide: ExtendedContendChildrenService,
    useClass: ExtendedContendChildrenService
  } as Provider;
};

export class ExtendedContendChildrenService<T extends Type<Q>, Q extends BaseContentChildrenComponent> {
  registeredElements = new BehaviorSubject<{
    type: T,
    instance: Q
  }[]>([]);

  registerElement(instance: Q) {
    const currentElements = this.registeredElements.getValue();
    const existingIndex = currentElements.findIndex(element => element.instance === instance);

    if (existingIndex !== -1) {
      const updatedElements = [...currentElements];
      updatedElements[existingIndex] = {
        type: instance.constructor as T,
        instance
      };
      this.registeredElements.next(updatedElements);
    } else {
      this.registeredElements.next([...currentElements, {
        type: instance.constructor as T,
        instance
      }]);
    }
  }

  removeElement(instance: InstanceType<T>) {
    const currentElements = this.registeredElements.getValue();
    this.registeredElements.next(currentElements.filter(el => el.instance !== instance));
  }
}

I have created a BaseClass which when extended from registers itself to the Service (see above).

@Directive()
export class BaseContentChildrenComponent {
  extendedContendChildrenService = inject(ExtendedContendChildrenService);
  elementRefBaseContentChildren = inject(ElementRef);
  renderer2 = inject(Renderer2);

  constructor() {
    inject(DestroyRef).onDestroy(() => {
      this.extendedContendChildrenService.removeElement(this);
    });
    this.renderer2.setAttribute(this.elementRefBaseContentChildren.nativeElement, 'app-extended-content-children', "");
    this.extendedContendChildrenService.registerElement(this);
  }

}

Finally I have a “contentChildrenExtended” function which ties those components together:


function walkExtendedContent(rootNode: Node, options: { desc: boolean } | undefined): Element[] {
  const foundElements: Element[] = [];
  const treeWalker = document.createTreeWalker(
    rootNode,
    NodeFilter.SHOW_ELEMENT,
    {
      acceptNode: function (node: Element) {
        if (options?.desc === false || options === undefined || options.desc === undefined) {
          for (const foundElement of foundElements) {
            if (foundElement.contains(node) && node !== foundElement) {
              return NodeFilter.FILTER_REJECT;
            }
          }
        }

        if (node.hasAttribute('app-extended-content-children')) {
          foundElements.push(node);
        }
        return NodeFilter.FILTER_ACCEPT;
      }
    }
  );

  let currentNode: Element | null = treeWalker.nextNode() as Element;
  while (currentNode) {
    currentNode = treeWalker.nextNode() as Element;
  }

  return foundElements;
}

export const contentChildrenExtended = <T extends Type<BaseContentChildrenComponent>>(type: T[] | T, options?: {
  desc: boolean
}) => {
  const types = coerceArray(type); // Please note this is from angular/cdk if you don't have this in your project create your own coerceArray
  const contentChildrenService = inject(ExtendedContendChildrenService);
  const searchHost = inject<ElementRef<HTMLElement>>(ElementRef);
  const destroyRef = inject(DestroyRef); // Inject DestroyRef for cleanup
  const subject = new Subject<Element[]>();
  const mutationObserver = new MutationObserver(() => {
    subject.next(walkExtendedContent(searchHost.nativeElement, options))
  });
  mutationObserver.observe(searchHost.nativeElement, {
    attributeFilter: ['app-extended-content-children'],
    subtree: true,
    childList: true
  });
  destroyRef.onDestroy(() => {
    mutationObserver.disconnect();
    subject.complete();
  });
  return toSignal(
    combineLatest([
      contentChildrenService.registeredElements,
      subject.pipe(
        debounceTime(0),
        startWith(walkExtendedContent(searchHost.nativeElement, options))
      )
    ]).pipe(
      map(([registeredElements, possibleHtmlElements]) => {
        const filteredRegisteredElements = registeredElements.filter(registeredElement =>
          types.includes(registeredElement.type as T)
        );
        return filteredRegisteredElements.filter(registeredElement =>
          possibleHtmlElements.includes(registeredElement.instance.elementRefBaseContentChildren.nativeElement)
        );
      }),
      map(filteredRegisteredElements =>
        filteredRegisteredElements.map(registeredElement => registeredElement.instance as InstanceType<T>)
      ),
      map(result => result || [])
    )
    , {initialValue: []})
}

Please see following example which can be used as a starting point:

Extended Content Children in Angular

Overview

This is a workaround solution for scenarios where Angular’s standard @ContentChildren decorator doesn’t meet your needs, particularly when dealing with dynamic content, deeply nested components, or complex component hierarchies.

Note: This solution is designed for web applications and may not work with Ionic or other native wrappers.

Key Features

  • Dynamic content detection
  • Deep nesting support
  • Proper scoping of parent-child relationships
  • Automatic cleanup on component destruction
  • Support for filtered queries (by component type)
  • Observable-based updates

Implementation Components

1. Service Provider

export const provideExtendedContendChildrenService = () => {
  return {
    provide: ExtendedContendChildrenService,
    useClass: ExtendedContendChildrenService
  } as Provider;
};

The service maintains a registry of components and handles their lifecycle.

2. Base Component/Directive

@Directive()
export class BaseContentChildrenComponent {
  extendedContendChildrenService = inject(ExtendedContendChildrenService);
  elementRefBaseContentChildren = inject(ElementRef);
  renderer2 = inject(Renderer2);

  constructor() {
    // Auto-registration and cleanup
    inject(DestroyRef).onDestroy(() => {
      this.extendedContendChildrenService.removeElement(this);
    });
    this.renderer2.setAttribute(
      this.elementRefBaseContentChildren.nativeElement, 
      'app-extended-content-children', 
      ""
    );
    this.extendedContendChildrenService.registerElement(this);
  }
}

All components that need to be queried should extend this base class.

Usage Examples

Basic Usage

// Child component
@Component({
  selector: 'app-child',
  standalone: true
})
export class ChildComponent extends BaseContentChildrenComponent {
  @Input() data: string;
}

// Parent component
@Component({
  selector: 'app-parent',
  standalone: true,
  providers: [provideExtendedContendChildrenService()]
})
export class ParentComponent {
  children = contentChildrenExtended(ChildComponent);
}

Complex Nested Example

@Component({
  selector: 'app-complex',
  template: `
    <app-parent>
      <div *ngFor="let item of items">
        <app-child [data]="item">
          <app-parent>
            <app-child [data]="'nested-' + item"></app-child>
          </app-parent>
        </app-child>
      </div>
    </app-parent>
  `,
  providers: [provideExtendedContendChildrenService()]
})
export class ComplexComponent {
  items = ['A', 'B', 'C'];
}

Multiple Component Types

@Component({
  selector: 'app-container',
  providers: [provideExtendedContendChildrenService()]
})
export class ContainerComponent {
  allChildren = contentChildrenExtended([TypeA, TypeB, TypeC]);
}

Best Practices

  1. Service Provision

    • Provide the service at the component level where you want to query children
    • Each provider creates a new scope for child detection
  2. Component Extension

    • Always extend BaseContentChildrenComponent for components you want to query
    • Make sure to call super() if implementing custom constructors
  3. Performance Considerations

    • The solution uses MutationObserver, so be mindful of deeply nested structures
    • Use the desc option to control descendant scanning behavior
    contentChildrenExtended(MyComponent, { desc: false }) // Only direct children
    
  4. Cleanup

    • Automatic cleanup is handled via DestroyRef
    • No manual cleanup needed for normal scenarios

Common Use Cases

  1. Dynamic Tabs
@Component({
  selector: 'app-tab-group',
  template: `
    <div class="tabs">
      <ng-container *ngFor="let tab of tabs()">
        {{tab.label}}
      </ng-container>
    </div>
    <ng-content></ng-content>
  `,
  providers: [provideExtendedContendChildrenService()]
})
export class TabGroupComponent {
  tabs = contentChildrenExtended(TabComponent);
}
  1. Form Field Containers
@Component({
  selector: 'app-form-container',
  providers: [provideExtendedContendChildrenService()]
})
export class FormContainerComponent {
  formFields = contentChildrenExtended([
    InputFieldComponent,
    SelectFieldComponent,
    CheckboxFieldComponent
  ]);
}

Limitations

  1. Web-only solution (not compatible with native wrappers)
  2. Relies on DOM manipulation and MutationObserver
  3. May have performance impact with very large component trees
  4. Requires extending a base class (might conflict with other inheritance needs)

Debugging Tips

  1. Check component registration:
constructor(private service: ExtendedContendChildrenService) {
  service.registeredElements.subscribe(console.log);
}
  1. Verify attribute presence:
ngAfterViewInit() {
  console.log(
    this.elementRef.nativeElement.querySelector('[app-extended-content-children]')
  );
}

In case this proofs useful to some I might create a small NPM Package where we also could experiment with CSS - Selectors additionally to types. E.g. contentChildrenExtended(“p > [app-option]”) or with contentChildExtended(“.find-first-only”)

Hundreds of upvotes and 6 years are not enough… At least we have deprecated NgModules and class-based guards… WIth High priority…

Same case as in this one: https://github.com/angular/angular/issues/10887

😄

I have tried the workaround explained in the @edpeng comment but it does not work in my use case, maybe because of some implementation details of the PrimeNG Tree (I don’t know).

But I have found a very strange behaviour: at first when I check @ViewChildren in the @ngOnAfterViewInit it contains the children components (7), but after that the array becomes empty. I’m not sure, but it seems like the parent templates overwrite the child view.

image

(first variable is the @ViewChildren and second is the @ContentChildren)


EDIT: I have tried saving the initial @ViewChildren in a variable so I can manipulate it later, but it does not the trick because the change detection and template references get broken.

The only workaround I found is manipulating the children components with @ContentChildren { descendants: true } in the parent component, but it is not a clean solution considering the parent component should be able to set custom templates and these should be used in the child component.

Anyway it has a strange behaviour also, as the @ContentChildren is empty at first in the ngOnContentInit and then is filled with the projected templates. It does not make sense to me.

The good news is that at least it works and the user interface is in sync.

Definitely we would need an straightforward solution for this in Angular.

Encountered similar issue in Angular v6.0.0. Found this workaround based on subscribing to QueryList changes - similar to what @robertbrower-technologies suggested? I had to add an extra step to call ngDoCheck() because subscribe didn’t work when using *ngIf:

<div *ngIf="isPageLoaded">
<parent [template1]="template1"></parent>
</div>
export class Parent implements OnInit, AfterContentInit, DoCheck  {
    @ContentChildren(Child) children: QueryList<Child>()
    ...
    ngAfterContentInit(): void {
        console.log('expecting length to be initially 0. length:' + children.length);
        this.children.changes.subscribe( c => console.log('length is now:' + children.length);
    }
    ngOnInit(): void {
       setTimeout(() => {console.log('timer ran doCheck()');this.ngDoCheck()}, 0);
    }

  ngDoCheck(): void {
    console.log('ran docheck');
  }
}

@feco93 For future reference he got the component reference by assigning it in the child’s constructor: constructor(elem: ElementRef) { elem.nativeElement.component = this; }