Angular: possible to queries elements of all DOM from a specific component?

606 views Asked by At

With the DOM snippets below:

<ng-app>
  <ng-comp1></ng-comp1>
  <ng-comp2>
     <ng-comp3></ng-comp3>
  </ng-comp2>
  <ng-comp1></ng-comp1>
</ng-app>

I would like from ng-comp3 to list all components ng-comp1 in DOM document. There is a way for that ?

ViewChildren list only components inside ng-comp3.

document.querySelector list DOM element, not the component.

1

There are 1 answers

3
Guilhermevrs On

The short answer is "No, you cannot directly list them".

What you can do, on the other hand, is to have the ng-app injected in your ng-comp3 component and interact with the ng-comp1 via the ng-app.

I have put an example here

@Component({
  selector: 'inner-hello',
  template: `<h1>Hello {{name}}!</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class InnerHelloComponent implements AfterViewInit  {
  @Input() name: string;

  constructor(@Inject(forwardRef(() => AppComponent)) private app: AppComponent) {
    console.log(app.name);
  }

  ngAfterViewInit() {
    // Here you will be able to access your ViewChild
  }
}

Don't forget that the ViewChild and ViewChildren do not get populated until ngAfterViewInit gets fired

The idea, as may have noticed, is to query for ng-comp1 in the ng-app component, store that in a public variable and access it from the ng-comp3. The same way I am accessing the property name in my example