How to get table header onClick to row cell in html table?

I have a table with checkboxes, I want to get table header of a specific row cell on click to checkboxes in table row cells. It will only return the header where the clicked cell is. I am trying to do something like this: https://stackblitz.com/edit/angular-ivy-5dgmxy?file=src%2Fapp%2Fapp.component.ts

 <table class="table">
    <thead>
      <tr >
        <th></th>
        <th scope="col" *ngFor="let columnNames of tableHeaderNames">{{columnNames}}</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let role of roles; let i = index">
        <td >{{role}}</td>
        <td ><input (click)="select($event)" type="checkbox"></td>
        <td ><input (click)="select($event)" type="checkbox"></td>
        <td ><input (click)="select($event)" type="checkbox"></td>
        <td ><input (click)="select($event)" type="checkbox"></td>
        <td ><input (click)="select($event)" type="checkbox"></td>
        
      </tr>
    </tbody>
  </table>
import { Component, VERSION } from "@angular/core";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  name = "Angular " + VERSION.major;
  public tableHeaderNames = [
    "Header1",
    "Header2",
    "Header3",
    "Header4",
    "Header5"
  ];
  public roles = [
    "Role1",
    "Role2",
    "Role3",
    "Role4",
    "Role5",
    "Role6",
    "Role7"
  ];

  select(e) {
    console.log(e)
  }
}

Answer

As you’re already hardcoding in the td elements you could just pass a value into the click function, like:

<td ><input (click)="select($event, 0)" type="checkbox"></td>
<td ><input (click)="select($event, 1)" type="checkbox"></td>
<td ><input (click)="select($event, 2)" type="checkbox"></td>

Then the select function gets the index as the second value and looks up the corresponding tableHeaderNames value, like:

select(e, index) {
    console.log(this.tableHeaderNames[index])
}

Additionally, a better way to do this without hardcoding is to generate the td elements dynamically per the number of header elements there are. You can then pass in the header name directly into the select function, like so:

<tr *ngFor="let role of roles">
  <td>{{ role }}</td>
  <td *ngFor="let roleColumn of tableHeaderNames; let i = index">
    <input (click)="select($event, roleColumn)" type="checkbox">
  </td>
</tr>

I can dynamically pass through the roleColumn value which will contain the header name.

Leave a Reply

Your email address will not be published. Required fields are marked *