Tips for passing the indexes of an array within nested ngFor loops in Angular

I have a 2D grid in my component that is created using nested ngFor loops, and I want to make certain grid elements clickable under specific conditions so they can call a function. Is there a way for me to pass the index of the clicked array element to the associated function when setting up the href attribute? The array has three possible states: undefined, true, or false. The grid is displaying correctly, but I am struggling to figure out how to determine which square was clicked.

This is the base class structure:

export abstract class BaseGrid implements OnInit {
  aGrid: (boolean | undefined)[][];
  ...
}

The TypeScript code for the component is as follows:

import { Component, OnInit } from '@angular/core'
import { BaseGrid } from '../base-grid/base-grid.component';

@Component({
  selector: 'display-my-grid',
  templateUrl: './my-grid.component.html',
  styleUrls: ['./my-grid.component.css']
})

export class MyGrid extends BaseGrid implements OnInit {

  constructor() {
    super();
  }

  ngOnInit() {
  }
}

And here's the template code:

<table class="mybg">
  <tr *ngFor="let aRow of aGrid">
    <td *ngFor="let anElement of aRow">
      <div *ngIf="anElement === undefined" class="elementDiv"><a href="#"><img src="../../assets/transparentGif.gif" class="openElement" /></a></div>
      <div *ngIf="anElement !== undefined && anElement === false" class="elementDiv"><img src="../../assets/aMarker.gif" class="elementMarker" /></div>
      <div *ngIf="anElement !== undefined && anElement === true" class="elementDiv"><img src="../../assets/bMarker.gif" class="elementMarker" /></div>
    </td>
  </tr> 
</table>

Answer №1

Utilize the index property offered by the *ngFor directive. Take a look at the example provided below:

<table class="mybg">
  <tr *ngFor="let aRow of aGrid; let rowIndex = index">
    <td *ngFor="let anElement of aRow; let elementIndex = index">
      <div *ngIf="anElement === undefined" class="elementDiv"><a href="#"><img src="../../assets/transparentGif.gif" class="openElement" /></a></div>
      <div *ngIf="anElement !== undefined && anElement === false" class="elementDiv"><img src="../../assets/aMarker.gif" class="elementMarker" /></div>
      <div *ngIf="anElement !== undefined && anElement === true" class="elementDiv"><img src="../../assets/bMarker.gif" class="elementMarker" /></div>
    </td>
  </tr> 
</table>

rowIndex will provide you with the row index of your array, while elementIndex will give you the index of the element within that row. These can be used for various actions as needed.

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

Having trouble troubleshooting the jQuery button

When I click this button, it triggers an ajax call that updates the score_up value. I can't seem to figure out what's wrong. I attempted using Firebug, but it doesn't detect the JavaScript. Any help would be appreciated! Here is the jQuery ...

AInspector WCAG evaluation found that mat-select does not meet level A compliance standards

As I work on making my website WCAG level A compliant, I've encountered an issue with the mat-select component in Angular material. After running checks with the AInspector extension for Firefox, it appears that the mat-select component lacks aria-con ...

Using JavaScript to parse JSON response for sending status data through a POST request

I have successfully implemented a PHP code for file uploads. However, I am facing an issue retrieving the JSON response that indicates the upload status. Upon uploading a file via POST method, the response appears as follows: {"html_content":"<p>Fi ...

The functionality of the String prototype is operational in web browsers, but it encounters issues

Version: 8.1.0 The prototype I am working with is as follows: String.prototype.toSlug = function () { return (<string>this) .trim() .toLowerCase() .replace(/\s+/g, '-') .replace(/[^\w\-]+/g, '') ...

Ending an $.ajax request when the page is exited

Currently, I have a function set on a timer to retrieve data in the background: (function fetchSubPage() { setTimeout(function() { if (count++ < pagelist.length) { loadSubPage(pagelist[count]); fetchSubPage(); ...

Use PipeTransform to apply multiple filters simultaneously

Is it possible to apply multiple filters with PipeTransform? I attempted the following: posts; postss; transform(items: any[]): any[] { if (items && items.length) this.posts = items.filter(it => it.library = it.library ...

Can you explain the term 'outer' in the context of this prosemirror code?

Take a look at this line of code from prosemirror js: https://github.com/ProseMirror/prosemirror-state/blob/master/src/state.js#L122 applyTransaction(rootTr) { //... outer: for (;;) { What does the 'outer' label before the infinite loop ...

Implementing XOR operation in a jQuery script

In need of a small script modification where one value needs to be XORed. A previous suggestion no longer applies due to changes made in the script. <input type='button' value='Ein / Aus' class='taster' csv='Lampe&apo ...

The Auth0 callback function is functioning properly in the development environment of my Angular 2 (4) application

While testing my Angular 4 login with Auth0 in development mode using localhost:4000/callback as the redirectUri for my auth0.WebAuth, everything works smoothly. However, when transitioning to production and changing the redirectUri = https://example.com/ ...

Customize Popover Color in SelectField Component

Looking to customize the SelectField's popover background color in material-ui. Is this possible? After exploring the generated theme, it seems that there is no option for configuring the selectField or popover. Attempted adjusting the menu's ba ...

The error message "Unable to access 'useContext' property of null" appeared

I am currently in the process of developing a component library using Material UI, TypeScript, and Rollup. The package has been successfully published, but I am encountering an error when trying to import it into a new project: "Uncaught TypeError: C ...

Integrating new components into JSON data

I started by creating a JSON document in my code using the following syntax: let jsonData = []; To populate this document, I utilized the '.push()' method to add elements in this manner: jsonData.push({type: "example", value: "123"}); Eventua ...

Sharing functions between Angular components

Check out my problem statement: https://stackblitz.com/edit/angular-jk8dsj I'm facing two challenges with this assignment: I need to dynamically add elements in the app.component when clicking a button in the key-value.component. I've tried ...

Typescript's interface for key-value pairing with generic types

Consider the example Object below: let obj1: Obj = { 'key1': { default: 'hello', fn: (val:string) => val }, 'key2': { default: 123, fn: (val:number) => val }, // this should throw an error, because the types of d ...

Implementing the MVC pattern in the app.js file for a Node.js and Express web application

After completing several tutorials on nodejs, mongodb, and express, I have gained a solid understanding of the basics such as: The main controller file being app.js. Third party modules stored in their designated node_modules directory. Template files pl ...

Error Message: Attempting to access the AngularJS injector before it has been initialized

Using AngularJS Service in an Angular 5 Component I have an existing AngularJS application and I am attempting to create a hybrid app. However, I am encountering difficulties using an AngularJS service within an Angular component, resulting in the followi ...

Encountered a problem while trying to set up the Angular Material Library that has been cloned from

Trying to setup a library that has been forked from https://github.com/angular/material2. git clone <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="63040a1723040a170b16014d000c0e">[email protected]</a>:vugar005/m ...

Using Javascript to define cookie values

I'm attempting to use JavaScript to set a cookie that will instruct Google Translate to select the language for the page. I've experimented with setting the cookie based on my browser's cookie selection of a language. <script> $(doc ...

I am looking to pair a unique audio clip with each picture in my collection

I have implemented a random slideshow feature that cycles through numerous images. I am now looking to incorporate a brief audio clip with each image, synchronized with the array I have established for the random pictures. The code snippet below is a simil ...

Altering the href text within a script causes the text to disappear instead of updating

Function Triggered by Button Click: function LoadEnglishText() { document.getElementById("txt_whatwedo_learnmore2").innerHTML = "here."; } HTML Link to be Updated: <a id="txt_whatwedo_learnmore2" href="./pdf/Pricing_App_Dev_2019_Ger.pdf">hier ...