Having trouble locating a nested component through multiple ng-content in Angular 8?

Currently, I am encountering an issue while attempting to locate components nested within sub child components.

To illustrate what I am aiming for, here is an example:

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);
  }
}

A complete example can be found at the following link: https://stackblitz.com/edit/angular-rqh8gm

I prefer not to utilize ngProjectAs since I aim to dynamically query elements.

Although I was able to locate the component through its parent component, I am curious if there is a method to re-append it to the grand parent component?

Answer №1

If you are looking to retrieve objects from the profile component, you must query it within the app-child component.

1) Attempting to find it in the Appcomponent will not work since it is not directly projected there.

2) By projecting it inside the app-child component, you will have access to it within that component.

3) Here is an example:

In the above scenario, comp3 is projected inside comp2 and not comp1. Direct projection functions properly in this context.

Take a look at these examples for more insight:

Example 1

If you want to access count in Appcomponent, try this method which involves multiple loops:

Example 2

This is my suggested approach, but feel free to share if you discover a better way to achieve this.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Inversify is a proven method for effectively injecting dependencies into a multitude of domain classes

Struggling to navigate dependencies and injections in a TypeScript-built rest web service without relying heavily on inversify for my domain classes, in line with the dependency inversion principle. Here's an overview of the project structure: core/ ...

Material Modules are causing issues with AOT compilation

I'm encountering multiple errors that all share a similar pattern: ERROR in ./node_modules/@angular/material/button/typings/index.ngfactory.js Module build failed: Error: Invalid name: "@angular/material/button" at ensureValidName (C:\path&b ...

Angular: Utilizing Parameters in HTTP GET Requests

I've recently started using Angular. Currently, I'm working on sending a parameter in an HTTP GET request. This is what my code looks like: for (var i = 0, len = this.recentArtists.topartists.artist.length; i < len && i < h ...

NextJS Typescript Layout is throwing errors due to the absence of required props

After following the instructions on https://nextjs.org/docs/basic-features/layouts#with-typescript and making changes to my Home page as well as _app.tsx, I encountered an issue with the layout file Layout.tsx. The provided guide did not include an exampl ...

Encountering "Cannot write file" errors in VSCode after adding tsconfig exclude?

When I insert the exclude block into my tsconfig.json file like this: "exclude": ["angular-package-format-workspace"] I encounter the following errors in VSCode. These errors disappear once I remove the exclude block (However, the intended exclusion fu ...

Enhance your viewing experience by zooming in and out with ng2-pdf-viewer

Currently, I am utilizing ng2-pdf-viewer to display PDF files within my application. <pdf-viewer [src]="pdfSrc" [page]="page" [zoom]="1.1" style="width: 100%;" I am looking to incorporate zoom in and zoom out buttons. Doe ...

Delivering an Angular2 application from a base URL using Express

I currently have an Angular2 application running alongside a simple express server. Is there a way to only display my application when a user navigates to a specific route, like '/app' for example? If so, how can this functionality be implemented ...

Improving the method of retrieving RTK result within getServerSideProps

Currently, I am utilizing RTK Query to make an API call within my getServerSideProps function. While I can successfully retrieve the result using the code snippet provided below, I find the process somewhat awkward. Additionally, the result lacks proper ty ...

Error: A cyclic dependency cannot be instantiated. The ApplicationRef ("[ERROR ->]") is occurring in the NgModule AppModule within ./AppModule@-1:-1

I recently implemented the following code in my app.module.ts file: providers: [ AppConfigService, { provide: APP_INITIALIZER, useFactory: (config: AppConfigService) => () => config.getAppConfig(), ...

A guide on implementing JSON data projection with TypeScript

{ "ClaimType": ["The 'Claim Type' should have a minimum length of 4 characters. You have only entered 2 characters."], "ClaimValue": ["The 'Claim Value' should have a minimum length of 4 characters. You have only entered 1 chara ...

Updating an item in the redux state is triggering a never-ending loop, leading to a browser

EXPECTED OUTCOME: My goal is to modify a value in my redux state ISSUE: I am encountering an issue where there is an infinite loop or the browser gets locked down. Despite consulting this Stack Overflow post and the official documentation, I am struggling ...

Guide to correctly passing custom parameters along with the event object to an asynchronous form submission handler

Asking for guidance on defining and typing custom parameters alongside the native event object in an async onSubmitHandler for a form. The current implementation only receives the native event as a single parameter: const onSubmitHandler: FormEventHa ...

I encountered a problem where the error "Type '(err: Error) => void' does not possess any properties similar to type 'QueryOptions'" appeared, and I am unsure of the underlying cause

Check out my route for removing a user: https://i.stack.imgur.com/fevKI.png I've set up a route called "/deleteuser" that uses the POST method. It validates the request body for an id and then proceeds to delete the user with that ID from the databas ...

Is it possible to utilize ngIf to reuse a component when encountering a 404 error? How can the error be captured?

In my app-routin.module.ts file, I have a root component named HomeComponent that I reuse for unknown routes. const routes: Routes = [ { path: '', component: PrimaryComponent, data: { breadcrumb: 'PRIMARY'}, children: [ { p ...

Tips for implementing a cascading dropdown feature in Angular 7 Reactive Formarray: Ensuring saved data loads correctly in the UI form

I recently found a helpful guide on stackoverflow related to creating cascading dropdowns in an Angular reactive FormArray, you can check it out here After following the instructions, I managed to achieve my desired outcome. However, I now face a new chal ...

Utilizing the component within the template could potentially result in a cyclical dependency if it were to be imported

I have encountered an issue with two components that reference each other in a recursive manner. Ever since I upgraded to Angular 13, I am unable to use it and I keep receiving the error mentioned in the title. Component A (field.component.html): <app- ...

Having trouble rendering an object in my ThreeJS project. The error message says: "THREE.OBJLoader: Unexpected line: 'usemap glass'"

I encountered an error while running threejs in an angular 8 application. The objective is to load an object, for which the object and material files were obtained from Kenney assets. Despite referencing examples on the official threejs site and other onli ...

What could be causing the conditional div to malfunction in Angular?

There are three conditional div elements on a page, each meant to be displayed based on specific conditions. <div *ngIf="isAvailable=='true'"> <form> <div class="form-group"> <label for ...

What causes TypeScript's ReadonlyArrays to become mutable once they are transpiled to JavaScript?

Currently, I am in the process of learning Typescript by referring to the resources provided in the official documentation. Specifically, while going through the Interfaces section, I came across the following statement: TypeScript includes a special t ...

Navigating to Angular components within a statically hosted S3 application

I am in the process of creating an application using Angular4 on the frontend. The main objective for deployment is to serve the frontend as static content from an AWS S3 bucket. Everything seems to be working smoothly except for one crucial issue. When u ...