Humaid
Humaid

Reputation: 13

Angular 8: issue finding component nested through multiple ng-content

I am facing this issue when trying to find components nested within sub child components.

I have created an example of what I want to achieve:

import { Component, OnInit, ContentChildren, ElementRef, QueryList } from '@angular/core';


@Component({
  selector: 'app-grand-parent',
  template: '<ng-content></ng-content>',
})
export class GrandParentComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }

}

@Component({
  selector: 'app-parent',
  template: '<ng-content></ng-content>',
})
export class ParentComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }

}


@Component({
  selector: 'app-child',
  template: '<ng-content></ng-content>',
})
export class ChildComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }

}


@Component({
  selector: 'app-child-profile',
  template: '<div>Child Profile</div>',
})
export class ChildProfileComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }

}

@Component({
  selector: 'my-app',
  template: `
  <div>
  <app-grand-parent>
    <app-parent>
      <app-child>
      <app-child-profile></app-child-profile>
      <app-child-profile></app-child-profile>
      <app-child-profile></app-child-profile>
      </app-child>
    </app-parent>
  </app-grand-parent>
</div>`
})
export class AppComponent implements AfterContentInit  {
  @ContentChildren(ChildProfileComponent) profiles: QueryList<ChildProfileComponent>;

  ngAfterContentInit(): void {
    console.log(this.profiles);
  }
}

There is a full example in the following link: https://stackblitz.com/edit/angular-rqh8gm

I don't want to use ngProjectAs as I want to dynamically query elements.

I could find the component through its parent component. Is there is a way to re-append it to grand parent component?

Upvotes: 1

Views: 502

Answers (1)

Passionate Coder
Passionate Coder

Reputation: 7294

For getting objects of profile component. You need to query it inside app-child component

1) You are finding it in Appcomponent but its not directly projected in it so you will not able to find it

2) You are projecting it inside app-child so this will be available inside app-child

3) Example

In above case comp3 is projected inside comp2 not in comp1. Direct projection works here

Have a look

https://stackblitz.com/edit/angular-hwv8g7?embed=1&file=src/app/app.component.ts

Try this if you want access count in Appcomponent. For this you have to go through mulltiple loops

https://stackblitz.com/edit/angular-shh1up?embed=1&file=src/app/app.component.ts

This is my approach do let me know if you find some better way

Upvotes: 2

Related Questions