Using two indexes in ngFor can result in unexpected changes to the values being displayed

I am currently working on printing checkboxes and facing an issue with initializing the id and name attributes using ngFor. The values I'm getting are incorrect.

Let's consider 2 arrays (or n arrays retrieved from a database):

animal = 'dog', 'cat'

vehicle = 'bus', 'plane', 'train'

If I use 2 ngFor loops, it should iterate as follows (i, j being the indices):

i = 0 , j=0 > i = 0, j = 1

The next row should be:

i = 1, j = 0 > i = 1, j = 1 > i=1, j = 2

Below is a snippet of my code :

<form>
  <div class="form-group row" *ngFor="let firstColumn of mapMenusFirstColumn; index as i">
    <label class="col-4">{{firstColumn}}</label>
    <div class="col-8">
      <div class="custom-control custom-checkbox custom-control-inline" *ngFor="let secondColumn of this.getSecondColumn(this.mapMenu,firstColumn); index as j">
        <input name= {{i}}  id={{i+'_'+j}} type="checkbox" class="custom-control-input" value={{secondColumn}}>
        <label for={{i+'_'+j}} class="custom-control-label">{{secondColumn}}</label>
      </div>
    </div>
  </div>
</form>

In this scenario, the name attribute should correspond to the following ids:

name should be 0 -> when id 0_0

name should be 0 -> when id 0_1

name should be 1 -> when id 1_0

name should be 1 -> when id 1_1

name should be 1 -> when id 1_2

[I have not included actual data due to its size (n rows), only provided a screenshot]

When I assign the id and name as both i:

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

However, when I set i as the name (since for 3/4 checkbox items, the name should be same) and j as the id:

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

It appears that i is in the position of j. I have attempted swapping i and j positions, but it did not resolve the issue.

I would appreciate insights on alternative implementations as well.

Answer №1

Through trial and error, I stumbled upon a solution that worked for me

The only change needed was -

  1. I had to include trackby
  2. When writing a string, I used double quotes " " for both id and name

[ Although it's still a string within interpolation {{ }}, I couldn't figure out why it worked. Your explanation would be highly appreciated ]

<form>
  <div class="form-group row" *ngFor="let firstColumn of mapMenusFirstColumn; index as i;">
    <label class="col-4">{{firstColumn}}</label>
    <div class="col-8">
      <div class="custom-control custom-checkbox custom-control-inline"
        *ngFor="let secondColumn of this.getSecondColumn(this.mapMenu,firstColumn); index as j;">
        <input name="checkbox{{i}}" id="checkbox{{i+'_'+j}}" type="checkbox" class="custom-control-input"
          value={{secondColumn}}>
        <label for="checkbox{{i+'_'+j}}" class="custom-control-label">{{secondColumn}}</label>
      </div>
    </div>
  </div>
</form>

In my .ts

  trackByFn(i: number) {
    return i;
  }

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

Utilizing AngularJS and RequireJS for intricate routing within web applications

I have encountered an issue with nested routings that I am struggling to resolve. The technologies I am using include: AngularJS, RequireJS; AngularAMD, Angular Route. To start off, here is my main routing setup: app.config(function($routeProvider, $loc ...

A guide on extracting keywords from the tynt API using JavaScript

Looking to extract the inbound keyword from an API: What would be the best way to use JavaScript to extract and display the value of the inbound keyword from this API? ...

Guide to populating a dropdown list using an array in TypeScript

I'm working on a project where I have a dropdown menu in my HTML file and an array of objects in my TypeScript file that I am fetching from an API. What is the best approach for populating the dropdown with the data from the array? ...

Optimal method for populating table filter values from query string in Typescript while handling asynchronous calls

Using Typescript for Angular, I am dealing with a table that has filters in the form of drop downs. The data for each filter is retrieved asynchronously from the backend. My challenge is to load the data for all filters while setting default values based o ...

What is the best way to visualize the PerspectiveCamera in three.js?

Upon diving into the tutorial on drawing lines in three.js documentation, I came across some intriguing code snippets: All seemed well and good with the code. <html> <head> <meta charset="utf-8"> <title&g ...

Is the data fetched by getStaticProps consistently the same each time I revisit the page?

When utilizing routes to access a specific page like page/[id].js, the concern arises whether data will be refetched each time the page is visited. For instance, if you navigate to another page through a link and then return to this original page by pres ...

Deny access to the viewing feature for unauthorized users

Objective: To restrict access to the profile page only for logged-in users. The authentication is done through mongodb and passport-local. Existing Code: Below is the express route used to verify if the request is authenticated. app.get('/loggedin ...

Optimizing Angular6 Pipe Filter Performance for Large Arrays

I have written a filter that retrieves a subset of items from a large array consisting of around 500 items. import { Injectable, Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'searchFilter' }) @Inject ...

Removing HTML tags from Angular template bindings

My data list sometimes includes HTML elements <li *ngFor="let result of results"> <span [innerHTML]="result.question.title"> </span> </li> The issue with using innerHTML is that the HTML is parsed and rendered, affecting ...

JavaScript for varying content that is dynamically loaded on a completely ajax-powered website

This post has been updated to address the issue more effectively with a refined concept and code (based on the responses provided so far) I am working on developing an ajax-driven website, but I have encountered some issues with multiple bound events. He ...

Trouble accessing route parameter in sub module with Angular 9

I'm encountering an issue while attempting to access route parameters within a nested module. Our application consists of two modules: Project and Ticket. The Project module serves as the main module, while Ticket acts as a sub module. The route I a ...

What could be causing the issue of the view not showing up in AngularJS?

I've been trying to use AngularJS modules to display a view, but for some reason my page isn't showing up. Can anyone help me figure out what's going on? You can check out my code at the following link: <!DOCTYPE html> <html> & ...

Creating REST API Endpoint using Angular

Imagine having an Angular web app that displays a list of patients, the URL would be something like http://localhost:4200/patients. Is there a way to serve the same content (from the identical data source) in JSON format (application/json) by accessing ht ...

Determining the sequence of events for @HostListener event within an Angular directive

I am facing an issue with my Angular 9 application wherein a parent component contains a child component (referred to as "overview") which has a button. Upon clicking the button, the child component emits an event that should be handled by the parent compo ...

Create a unique custom design for your Mapbox GL control

When developing the website, we utilized Angular 8, Typescript, and SCSS. We are using mgl-map to display a map, and I wanted to create a custom control for it with unique styles. I added the custom control to the map using: const centerOnCoordinatesC ...

Submit button in the contact form fails to refresh upon being clicked

My website features a contact form with mandatory fields that users must fill out. If a user misses a field and is prompted to complete all fields, upon returning to fill everything out and clicking "send," nothing happens. The SEND button becomes unrespo ...

Tips for accessing the ID, Name and Class of a specific DIV element with the class "Extreme" upon clicking a button

Need help finding the ID of the outermost parent div <div class="panel" id="Kudapanel"> //Top-level Div <div class="Kudapanel1" id="Kudapanel1"> </div> <div> <div> <input type="button" id="yo ...

Combining Data from Header to Body using HTML5 and JavaScript

I am struggling to figure out how to transfer variables declared in the script from the header of my code to the body. Specifically, I want to capture the user input in the script and replace a placeholder in the body. Here is an example of what I am tryin ...

Converting a PHP array to a JavaScript array causes an issue of undefined variable when attempting to access a PHP array that has

I've been searching through other questions without finding the answer, so I'm reaching out for help with my specific issue. My problem is transferring a php array to a javascript array. In my code editor (phpStorm), I'm getting an error st ...

Recalling the layout following the user's computer restart

I am creating a simple online editing tool (similar to Microsoft Outline) for coursework and I would like the outline details to be saved even if the user restarts the system. How can I achieve this? <html> <head> <title>Editor</ ...