0
votes

Giving the following structure:

root:

<parent>
    <child>1st child content</child>
    <child>2nd child content</child>
</parent>

parent.html:

<ng-container *ngTemplateOutlet="children[currentChildIndex]"></ng-container><br/>

parent.ts:

export class ParentComponent implements OnInit {
  @ContentChildren(ChildComponent, { read: TemplateRef })
  set childrenQueryList(val: QueryList<ChildComponent>) {
    this.children = val.toArray();
  }
  children;
  currentChildIndex = 0

child.html:

<ng-content></ng-content>

child.ts:

public foo() {
    alert(`foo`)
  }

when I'm trying to call a child method from the parent like:

this.children[0].foo()

I'm getting

Cannot read property 'foo' of undefined

and, of course, the children aren't showing.

Not working example

1
your demo link does not seem to have any parent child components - ABOS
Fixed. Thank you - Eylon Sultan
@ContentChildren(ChildComponent, { read: TemplateRef }), you should not read TemplateRef; try remove it and also in html file, using ngComponentOutlet - ABOS
@ABOS Thanks but it didn't work. Only after looking into angular materials impl. I figured it out - Eylon Sultan

1 Answers

0
votes

Apparently, you have to use ng-template and then show the template in the view.

Change child.html to have a template:

<ng-template><ng-content></ng-content></ng-template>

in child.ts add:

@ViewChild(TemplateRef) content: TemplateRef<any>;

in parent.html change to:

*ngTemplateOutlet="children[currentChildIndex].content"