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