GaborH
GaborH

Reputation: 719

How to get the column name and row name of a tablecell by clicking on the cell in angular4?

I would like to console log the column name and the row name of my clicked cell. I have created the following table, where the click event works for the 'timesroom' but not for the 'weekday' which gives an undefined response.

<table class="table table-bordered">
        <thead>
          <tr>
            <th *ngFor="let weekday of weekdays">
                <div>{{weekday}}</div>
            </th>
          </tr>
        </thead>
        <tbody>
          <tr scope="row" *ngFor="let time of times"><td>{{time}}</td>
            <th scope="row"></th> 
            <td (click) = "onClick(weekday, time)"></td>
            <td (click) = "onClick(weekday, time)"></td>
            <td (click) = "onClick(weekday, time)"></td>
            <td (click) = "onClick(weekday, time)"></td>
            <td (click) = "onClick(weekday, time)"></td>
          </tr>
         </tbody>
</table>

I believe the problem which I am facing is that the 'weekday' is out of scope. My question is how I should modify my code to be able to print both the 'weekday' and the 'time' on a cell click?

Upvotes: 0

Views: 1363

Answers (2)

GaborH
GaborH

Reputation: 719

The code which work for me is the following:

<table class="table table-bordered">
        <thead>
          <tr>
            <th *ngFor="let weekday of weekdays">
                <div>{{weekday}}</div>
            </th>
          </tr>
        </thead>
        <tbody>
          <tr scope="row" *ngFor="let time of times"><td>{{time}}</td>
            <th scope="row" *ngFor="let weekday of weekdaysForClick" (click) = "onClick(weekday, time)"></th> 
          </tr>
         </tbody>
</table>

I differentiate between two arrays: weekdays for the colum name which are the following( #, Monday, Thusday, Wednesday...) and weekdaysForClick(Monday, Thusday, Wednesday...).

Upvotes: 0

Mixalloff
Mixalloff

Reputation: 837

You need to repeat your td's using *ngFor and pass weekday into onClick handler

<thead>
  <tr>
    <th>Time</th>
    <th *ngFor="let weekday of weekdays">
      <div>{{weekday}}</div>
    </th>
  </tr>
</thead>
....
<tr *ngFor="let time of times">
    <td>{{time}}</td>
    <td *ngFor="let weekday of weekdays" (click) = "onClick(weekday, time)"></td>
 </tr>
....

Upvotes: 1

Related Questions