ContentChildren to gather all offspring

Currently, I am in the process of compiling a list of components using data from the Back End. I have implemented a ContentChild object to obtain their reference, however, it seems to be empty. I also attempted using ViewChild, but it only captures the first component.

Despite trying various solutions, none of them seem to work as expected. I suspect that this issue arises due to the fact that the child components are generated after the class is initialized (though I could be mistaken).

This is the code snippet of what I have done so far:

table.component.ts

export class tableComponent {
  @ContentChildren('relation') relationElements: QueryList<RelationElement>;
}
  colapseColumn(){
    this.table.resetChildElements();
    console.log(this.relationElements);

  }

table.component.html

<ng-container *ngFor="let entity of table.tableEntity">
    <tr class="listTable--bodyRow" >
        <td class="listTable--bodyElement"
            *ngFor="let element of entity.printableElements">
            <container-relation
                #relation
                [element]="element"
                (collapseColumn)="colapseColumn();">
            </container-relation>
       </td
   </tr>
</ng-container> 

UPDATE

After attempting with ViewChildren:

@ViewChildren('relation') relationElements: QueryList<any[]>;

Upon inspecting the output of relationElements, I receive the following result:

QueryList {_dirty: false, _results: Array(0), _emitter: EventEmitter

The desired outcome should enable me to perform actions like:

this.relationElements.map(re => re.extended = false);

Answer №1

If you're working with the QueryList class, you can make use of the Observable changes property to receive notifications whenever a component is added or removed. It's recommended to utilize @ViewChildren() over @ContentChildren(), especially if your template doesn't include any ng-content.

@ViewChildren('relation')
relationElements: QueryList<RelationElement>;

ngAfterViewInit(){
  this.relationElements.changes
    .startWith(this.relationElements).subscribe(()=>{
      console.log(this.relationElements);
      // perform actions upon list updates
    });
}

See it in action on plnkr

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

What is the process for creating mandatory fields in Angular?

I'm struggling to set all my fields as required so that when I click the Next button, the form submits and moves on to the next section. I want every field, whether it's a text box, checkbox, select option, or radio button, to be mandatory. ...

Inject a new observable into the current Subject

Having an Angular Subject named event$, I want to attach DOM controls as emitters to this observable when screens are loaded. The observable already has subscribers, so I am using a method to merge another observable with it, as shown below (Subscription m ...

Organize by a collection of strings or a collection of enums

Here is a list of objects that I have: enum MealType { Breakfast, Lunch, Dinner } interface FoodItem { name: string, type: MealType[], } const foodItems: FoodItem[] = [ { name: 'Pizza', type: [MealType.Lunch, MealType.Dinner ...

What is the process for invoking a service from a component?

I'm currently facing an issue with my service that is responsible for making HTTP requests and returning responses. The problem arises when I try to display parts of the response on the screen within my component, as nothing seems to be showing up des ...

The functionality of CDK Drag Drop is not accurately adjusting the placement of images

I have implemented an image gallery and am working on rearranging the position of the images using the Drag & Drop cdk library. However, I am facing an issue where the swapping of images does not always occur correctly; sometimes when attempting to exchan ...

I anticipated receiving an array of objects from the API response, but instead, I am dealing with an array of Promises in my React app using TypeScript

Apologies if this question seems basic to you. I am still new to TypeScript and working with Promises. Despite searching on various platforms, I couldn't find a relevant solution. Can you assist me in receiving an array of objects instead of promises? ...

What is the process for defining an opaque type in programming?

[ This is not this ] Take a look at this snippet of code: interface Machine<OpaqueType> { get(): OpaqueType, update(t: OpaqueType); } const f = <U, V>(uMachine: Machine<U>, vMachine: Machine<V>) => { const u = uMach ...

Unable to locate module in node_modules directory when attempting to import an image into TS

In my .tsx file, I am encountering an issue with the following code snippet: import L from 'leaflet'; import icon from 'leaflet/dist/images/marker-icon.png'; import iconShadow from 'leaflet/dist/images/marker-shadow.png'; The ...

Issue encountered while utilizing an observable object within a FormGroup

I've encountered an issue that I can't seem to resolve. I have a function that is responsible for creating my FormGroup along with the form fields and validators. The validators are custom validators that require a value from an observable, and t ...

Navigating between components in different modules using Angular 5

I have a home component within the homeModule and a contactUs component within the contactModule. When I click cancel on the contactUs component, it should redirect me to the Home component. Here are the routes: import {NgModule} from '@angular/cor ...

I am having trouble locating my TypeScript package that was downloaded from the NPM registry. It seems to be showing as "module not found"

Having some challenges with packaging my TypeScript project that is available on the npm registry. As a newcomer to module packaging for others, it's possible I've made an error somewhere. The following sections in the package.json appear to be ...

What steps can I take to concentrate on a particular mat-tab?

<mat-tab-group mat-stretch-tabs #tabGroup (focusChange)="tabChanged($event)" [selectedIndex]="0"> <mat-tab label="DATOS EXPEDIENTE"> <div class="example-large-box mat-elevation-z4"> <app-informe-expediente></app ...

Error handling: Encountered unexpected issues while parsing templates in Angular 2

I'm a beginner with Angular 2 and I'm attempting to create a simple module, but encountering an error. app.component.html import { Component } from '@angular/core'; import { Timer } from '../app/modules/timer'; @Component({ ...

Accessing dynamic data beyond the subscribe method function

Having some trouble creating a function that retrieves an object from a service using an external API. I'm struggling to get it functioning properly. FetchMatchInfo (matchId : number): Match { let retrievedMatch: Match; this.matchService.Ge ...

Tips for setting up a websocket connection between angular-socketio and flask-socketio

As a newcomer to web sockets, I am currently working on implementing a web socket server using flask-socketio for the server and angular-socketio for the client-side. For the server side in Flask, this is the code snippet I am using: application.py @ ...

What is the best way to set up role redirection following a successful login within my MEAN stack application?

I have successfully developed a MEAN stack application with a functioning backend and frontend. However, I am looking to enhance it further by implementing role-based redirection after login. There are 5 roles in the system: admin, teacher, nurse, sportsma ...

Divide the list of commitments into separate groups. Carry out all commitments within each group simultaneously, and proceed to the next group

My Web Crawling Process: I navigate the web by creating promises from a list of website links. These promises act as crawlers and are executed sequentially. For instance, if I have 10 links, I will crawl the first link, wait for it to complete, then move ...

Having trouble deleting a component from an array in React?

I am facing an issue with my array and component functions. Each component has a handleRemove function that is supposed to remove the selected component from the array. However, the function is not working as expected. Instead of deleting just the selected ...

Cucumber Wrangler

I am completely new to using protractor/cucumber and restler in Typescript. The code below is what I have so far for hitting an endpoint URL and getting the response: Given('Hit the {string}', async (string) => { browser.quit() var data: ...

When attempting to compile the building project following the upgrade to Angular 9, an error message is displayed stating "Unable to access property 'length' as it is undefined

I'm currently in the process of updating my Angular 9 project by following the migration guide on update.angular.io. After running ng update @angular/core @angular/cli, I encountered an error "ERROR in Cannot read property 'length' of undefi ...