Navigating Angular QueryList through loops

I am currently trying to gather all the images in my component and store them in an array. To achieve this, I am utilizing Angular's @ViewChildren which returns a QueryList of ElementRef:

@ViewChildren('img', { read: ElementRef }) images: QueryList<ElementRef>;

However, I am facing an issue while attempting to access the nativeElement when looping through the list. The code snippet below exemplifies this scenario within the ngAfterViewInit() method:

this.images.forEach((img, index) => console.log("Image", img.nativeElement));

Surprisingly, there is no output or error message displayed in the console log.

In contrast, when logging only the this.images, it functions correctly:

console.log("this.images", this.images);

For reference, an image showing the result of

console.log("this.images", this.images)
can be found here:

https://i.sstatic.net/t1zIw.png

The corresponding HTML structure is provided below:

<div class="swiper-slide" *ngFor="let exhibit of exhibits; let i = index">
           <app-exhibit-images exhibitImagesId="{{ exhibit.fields.eventImages[0].sys.id }}" [eventPicturesStart]="eventPicturesStart" (sendEndEventPictures)="getEndEventImages($event)"></app-exhibit-images>
           <div id="exhibit-{{i}}"class="gallery__content" [ngClass]="{'show-event-pictures' : eventPicturesStart}">
              <div class="gallery__poster" [ngClass]="{'gallery-expand' : isGalleryExpanded }">
                 <figure class="poster__image">
                    <picture>
                       <source srcset="{{ exhibit.fields.photo.fields.file.url }}" type="img/png">
                       <img #img src="{{ exhibit.fields.photo.fields.file.url }}" alt="{{ exhibit.fields.photo.fields.description }}">
                    </picture>
                 </figure>
              </div>
              <div class="gallery__text" [ngClass]="{'gallery-expand' : isGalleryExpanded }">
                 <button class="gallery-expand-button" (click)="expandGallery()"></button>
                 <h2 class="gallery__heading">{{ exhibit.fields.title }}</h2>
                 <h3 class="gallery__subheading">{{ exhibit.fields.subTitle }}</h3>
                 <h4 class="gallery__artist">{{ exhibit.fields.artist }}</h4>
                 <p class="gallery__description" *ngIf="exhibit.fields.description">{{ exhibit.fields.description }}</p>
              </div>
           </div>
        </div>

Am I overlooking something crucial?

Answer №1

I encountered a similar issue when using @ContentChildren. The workaround involved subscribing to the observable changes of the QueryList.

Basically, this subscription will trigger whenever there are changes in the state of the children. While typically not necessary, it becomes crucial if your list of children is fetched via a GET request, ensuring that the data in the QueryList is loaded before working with it. It's worth noting that the subscription will also fire again if any of the children's content changes.

@ContentChildren(forwardRef(() => ChildComponent), { descendants: true })
private children: QueryList<ChildComponent>;

ngAfterContentInit() {
    // subscribe to changes
    this.children.changes.subscribe(children => {
        children.forEach(child => {
            // perform operations on each child...
        });
    });
}

Answer №2

In addition to @Jakopo Sciampi's suggestion, you can also utilize the .toArray() method on the QueryList.

this.images.toArray().forEach((img, index) => {
            console.log('Image', img.nativeElement);
        });

It is important to ensure that you do not trigger the command prematurely, as this will result in no elements being present and the loop not being executed.

Answer №3

In my opinion, the correct way to handle this situation is:

this.images["_result"].forEach((img, index) => {
  console.log('Displaying Image:', img.nativeElement);
});

Answer №4

Avoid invoking your loop within the ngAfterViewInit method; opt for using ngAfterViewChecked instead. This will ensure that it runs after your child components have been checked.

For more information on Angular lifecycle hooks, please visit lifecycle-hooks

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 method for obtaining the most up-to-date JSON GET request URL?

Using JQGrid with search filters and setting loadOnce=false. I perform a search in the grid and observe the JSON request URL in firebug: http://localhost:8080/myapp/items/listGrid?ticketId=&_search=true&nd=1393573713370&rows=20&page=1& ...

Issue with routing in Angular 6 is caused by the "#" character

I am currently working on an Angular 6 project. In my app.routes, I have set it up like this. However, I am facing an issue where I can only access the route using localhost:4200/#/Student instead of localhost:4200/Student. Can you help me identify where t ...

How to store an imported JSON file in a variable using TypeScript

I am facing a challenge with a JSON file that stores crucial data in the following format { "login": { "email": "Email", "firstName": "First name", "lastName": "Last name", ...

Updating a div using PHP elements

Currently, I'm using a webcam to capture images for a project related to learning. My goal is to showcase the recently taken photos. After taking a photo, it gets stored in a folder. To display all the collected photos within a <div>, I need to ...

Retrieve the specific file path of a dependency within the node_modules directory

Can you help me find the exact path of a dependency within a specific node_modules package? Here's an example setup: |- node_modules/ |- <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d4a4b5b7bfb5b3b1f9b594e6fae5fae4"& ...

Startling error: Our node server.js running into an unexpected token

I'm attempting to follow the Angular Universal quickstart, but I encountered an error when running "node server.js". Emily's-MBP:vepo Emily$ node server.js /Users/Emily/Development/vepo/server.js:3 import 'angular2-universal/polyfills&apos ...

The Google Maps application is experiencing an issue with rendering maps

Here is my code without the google map key. I am not receiving any errors, but the map is not showing up. What could I be missing? To test it out yourself, you will need to add your own map key which you can obtain from here. <!DOCTYPE html> <h ...

No spaces are being retrieved from the input field

After entering "test data" in the first input box and clicking the submit button, only "test" is displayed in another input box. The goal is to have "test data" appear in the script-generated input box as well. Sample HTML Code <input name="" type="te ...

What could be causing Express to display a different page than the one specified in res.render?

Upon trying to view the compare.ejs page, I encountered an unexpected issue where a different page was being rendered instead. What could be causing this discrepancy? Here is my app.js code: var compare = require('./routes/compare')(nav); app.u ...

Drop-down selection triggering horizontal auto-scroll

Within my div element, I have a table with dropdowns. The div is set up to be horizontally scrollable. To create the dropdown functionality, I utilized Harvesthq Chosen. Let me provide some context. In Image 1, you'll notice that I've scrolled ...

Angular updates location, but browser redirects to incorrect page

I want my application to redirect non-logged in users to a login page. Following advice from a popular source, the app listens for routeChangeStart events like this: $rootScope.$on("$routeChangeStart", function(event, next, current) { if ($rootScope.c ...

Is it a problem with Cucumber Js callbacks or a feature issue?

I would like to create a scenario similar to this: Scenario: initialize new Singleton When an unmatched identity is received for the first time Then create a new tin record And establish a new bronze record And generate a new gold record This s ...

How can I center a Bootstrap modal vertically and make it responsive?

Is there a way to vertically center the bootstrap modal? I have been searching for a solution, but none seem to be responsive or effective. My website is using Bootstrap 3. The modal does not adjust properly on smaller screens or when the browser window i ...

Using Typescript to implement a conditional return type and ensuring that the value types are consistent together

I am working with a useSelectedToggle hook that helps in connecting the UI state to the open/closed status of a dialog where it will be displayed. The toggle defines the value as (T) when it is open, and null when it is closed. How can I enforce stricter ...

Transfer the elements from one array list to another array list

I need to duplicate the array list below $scope.medicinelist = [ {medicine: 'AMLOPRES 5MG TABLET'}, {medicine: 'ARGIPREG SACHET'}, {medicine: 'ALCIPRO 500MG TABLET'} , {medicine: 'PROLOMET AM 50MG TABLET'}, {medic ...

Encountering an Error during the Installation of MapBox SDK in React Native

After creating a React Native project with Expo using expo init MapTry, I encountered an issue while trying to install the MapBox library. Despite following the installation guide at https://github.com/rnmapbox/maps#Installation, I faced an error message w ...

The migration-mongo module is not being recognized as a standard CommonJS module

I have integrated a nodejs server component into my project, which includes the usage of migrate-mongo. In my package.json file, the type specified is module. However, when attempting to run the migration process, I encounter the following error: > migr ...

Video showcasing issue with updating Ionic2 view

I am encountering an issue where my View is not updating as expected. When a player makes a move, the triggers work (I did a console log on every update of the current game [1]), but the View does not update regularly. To investigate this problem, I added ...

Switching between various components based on conditions within the same route in Angular

My goal is to have 2 separate views, one for the homepage and another for authentication. I want to display the LoginComponent on the route '/' and the SignupComponent on the route '/signup' if the user is not logged in, otherwise rende ...

Is it possible to send data to the server in node.js before the page is loaded?

Once a user has logged in, their data is stored on the client side. There are certain pages that can be viewed without requiring a user to log in... For instance, I have created a route on node.js which generates a profile page based on a URL parameter. ...