簡體   English   中英

如何獲取表 header onClick 到 html 表中的行單元格?

[英]How to get table header onClick to row cell in html table?

我有一個帶有復選框的表格,我想在單擊表格行單元格中的復選框時獲取特定行單元格的表格 header。 它只會返回單擊單元格所在的 header。 我正在嘗試做這樣的事情: 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)
  }
}

由於您已經在td元素中進行了硬編碼,因此您可以將一個值傳遞給單擊 function,例如:

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

然后select function 獲取索引作為第二個值,並查找對應的tableHeaderNames值,如:

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

此外,無需硬編碼的更好方法是根據 header 元素的數量動態生成td元素。 然后,您可以將 header 名稱直接傳遞到select function 中,如下所示:

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

我可以動態傳遞包含 header 名稱的roleColumn值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM