0

I'm producing a 2D grid using nested ngFor for a property of my component, and under certain conditions I want grid elements to be clickable to call a function. Is there a way using this structure I can pass the indecis of the array that is clicked to the function call I'll associate with the href here? The array is basically a 2D tri-state (undefined, true, or false). The array is building out and displaying properly, but I'm having trouble figuring out how to pass which square is being clicked on from the grid.

In the base class that the component extends:

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

Here's the ts for the component:

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() {
  }
}

In the template:

<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>
0

1 Answer 1

2

Use the index property provided by *ngFor. See the example 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 give you your array's row index & elementIndex would be your element's index in that row. You can use them to perform any action.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.