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:

 <table class="table">
      <tr >
        <th scope="col" *ngFor="let columnNames of tableHeaderNames">{{columnNames}}</th>
      <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>
import { Component, VERSION } from "@angular/core";

  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
export class AppComponent {
  name = "Angular " + VERSION.major;
  public tableHeaderNames = [
  public roles = [

  select(e) {


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

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

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 *