How can one access DOM elements (getting and setting values) that are nested within an *ngFor loop?

How can I access the <span> and <select> elements in my code template shown below?

<div *ngFor="---">
  <div>
    <span></span>
    <select>
     <option></option>
     <option></option>
     <option></option>
    </select>
  </div>
</div>

Answer №1

Utilize QueryList and ViewChildren to fetch elements within *ngFor loop;

  ngAfterViewInit() {
    console.log(this.sp1)
  }

  @ViewChildren('swrapper') sp1: QueryList<any>;

HTML:

<div #wrapper> 
    <div *ngFor="---; i = index">
      <div>
        <span></span>
        <select [(ngModule)]="'selectElement' + i">
         <option></option>
         <option></option>
         <option></option>
        </select>
      </div>
    </div>
</div>

Answer №2

If you're working with Angular 2+, here's a handy technique you can utilize. Let's say you want to fetch Select elements, for example:

<div #wrapper> 
    <div *ngFor="---; i = index">
      <div>
        <span></span>
        <select [(ngModule)]="'selectElement' + i">
         <option></option>
         <option></option>
         <option></option>
        </select>
      </div>
    </div>
</div>

In the same component's .ts file, include:

 @ViewChildren('wrapper') wrapper: QueryList<any>;

To utilize this technique, all you need to do is:

this.wrapper

You can also access specific selectElement# elements by referencing the index in the *ngFor loop.

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

Ways to identify scroll occurrences within a mat-sidenav-container

Is there a way to detect the scroll event in Angular Material 2 when using mat-sidenav-container? I'm trying to call a method in my component whenever a user scrolls, but with mat-sidenav-container the scroll event doesn't work on the window any ...

Encountered an unexpected interpolation ({{}}) in column 3 of Data Bind RouterLink (Angular 2) that was expecting an expression

Encountering difficulties passing data to my routerLink. The goal is to change the route when the id reaches 4 within the ngFor loop. <input type="button" class="btn-cards" [ngClass]="getStyle(negociacao)" [routerLink]="['/{{negociacao.rota}}&apo ...

Facing problem with Angular 7 when making a GET request for non-JSON data

Currently, I am retrieving JSON data from a URL using the following method: this.http.get('http://localhost:3200/mydata').subscribe(data => { console.log(data); }); The response is in JSON format, and everything seems to be working fine. ...

A guide on altering the color of a badge through programming

I am curious to learn how I can dynamically change the color of a badge in Angular. My goal is to initially set the color of the badge to white, and then if the percVLRiskTotal reaches a specific value, change the color to green as an example. CSS: <sp ...

Check the attribute sequence in Angular HTML templates

Currently, our team is in discussions during code reviews regarding the order of attributes. We would like to find a way to streamline this process and believe that having support from an IDE or tool would be beneficial. Does anyone have recommendations f ...

Tips for modifying the JSON format within a Spring and Angular project

I am utilizing Spring for the backend and Angular for the frontend. Below is my REST code: @GetMapping(path = "/endpoint") public @ResponseBody Iterable<Relations> getGraphGivenEndpointId(@RequestParam(value = "id") int id) { return ...

The onRowSelect and onRowClick events are not being triggered on the Primeng table component in an Angular application

I am currently struggling to navigate to another component with the data selected when a row is clicked. I have been using p-table to accomplish this task. For some reason, neither onRowClick nor onRowSelection functions are being triggered. I even added ...

When comparing TypeScript class functions with regular functions and variables, which one yields better performance?

When it comes to defining functions, is it better to use variables or functions directly? Also, how does this affect tree-shaking? I am dealing with a lot of calculation-intensive helper classes and I am unsure about the optimal approach in terms of memor ...

Optimal Approach for Redirecting Authorization

I'm currently working on setting up an authorization feature for my Angular application. Here is the detailed process I am following: First, I generate a state and code in the front end. Upon clicking the login button, the application redirects to /a ...

the ngbPopover refuses to appear

I'm attempting to utilize the popover feature from ng-bootstrap in my Angular2/Typescript application, following the guidelines at here. Despite not encountering any errors, I am facing an issue where the popover does not appear. Here is the snippet ...

TypeScript and Next.js failing to properly verify function parameters/arguments

I'm currently tackling a project involving typescript & next.js, and I've run into an issue where function argument types aren't being checked as expected. Below is a snippet of code that illustrates the problem. Despite my expectation ...

A function's behavior will vary depending on whether it is a property of an object or not

I've been observing some peculiar behavior: In a typical scenario, TypeScript usually raises an error when an object contains too many keys, like this: type Foo = { a: string; } const a: Foo = { a: "hello", b: "foo" // Ob ...

A guide on incorporating ngFor with the flipping card feature in Angular

I am attempting to use ngfor to create some flip cards. However, the cards are not starting a new line and are overlapping in the first line. I have a total of 4 cards, but the 4th card is overlapping with the 1st card. I believe this issue is related to t ...

What steps can I take to resolve a CSS problem in an Angular Web Component within a React Application?

I recently integrated an Angular Web Component with some widgets from Angular Material UI into my simple React Application. While the functionality of the buttons, tables, and radio buttons is working perfectly fine, I am facing issues with the styling and ...

Using React along with TypeScript to specify the type of useState as an object containing key/value pairs of strings

I'm currently working in React with typescript and attempting to set the type of useState as an object containing string key/value pairs. Despite searching on SO, I haven't found a solution yet. I've experimented with <{ [key: string]: s ...

Unable to delete event listeners from the browser's Document Object Model

Issue at hand involves two methods; one for initializing event listeners and the other for deleting them. Upon deletion, successful messages in the console confirm removal from the component's listener array. However, post-deletion, interactions with ...

Adding an element to an array does not automatically reflect on the user interface

After fetching JSON data from the endpoint, I am attempting to update an array but not seeing the expected results on the frontend. export class LocationSectionComponent implements OnInit{ myControl = new FormControl(); options : string[] = [' ...

Hold off until the RxJS dispatch is resolved

I am working on integrating a "next step" feature into my Angular 6 webapp. When the user clicks the "next step" button, the frontend triggers an action to update the database with the data in the store, another action to retrieve processed data from a Spr ...

Modifying Font Style in Angular 4 Material

Is there a way to change the font in Angular 4 Material material.angular.io using the styles file in .CSS format instead of SASS? While the documentation offers an example for SASS at: https://github.com/angular/material2/blob/master/guides/typography.md ...

The Angular program is receiving significant data from the backend, causing the numbers to be presented in a disorganized manner within an

My Angular 7 application includes a service that fetches data from a WebApi utilizing EntityFramework to retrieve information. The issue arises when numeric fields with more than 18 digits are incorrectly displayed (e.g., the number 23434343434345353453,3 ...