@ViewChildren and @ContentChilrden. Creating components dynamically

54 Views Asked by At

I have two questions.

  1. I have a component ParentComponent inside it look like it:

@ContentChildren(ChildComponent) contentChildren!: QueryList<ContentChilrder>

@ViewChildren('childName') childNames!: QueryList<ElementRef>

Template looks like this:

<div class="container">
 <ng-content></ng-content>
</div>
<ng-container *ngFor="let contentChild of contentChildren">
  <p #childName>{{contentChild.name}}</p>
<ng-container>

So childNames is a list of of components that is used for navigation and it works The problem appears when instead of:

@ContentChildren(ChildComponent) contentChildren!: QueryList<ContentChilrder>

use

@ViewChildren(ChildComponent) contentChildren!: QueryList<ContentChilrder>

and in template:

<div class="container"
 <childComponent></childComponent>
 <childComponent></childComponent>
</div>

The name list is not generated. I was trying to subscribe to this.contentChildren.changes | async but it appears to be empty even though in console.log(this.contentChildren) I can see the list of the components.

  1. How Can I achive this while generating them dynamically with:

    viewTemplateRef.createComponent()

from a component tree structure that is for example a JSON or array.

0

There are 0 best solutions below