首页 > 解决方案 > 如何从使用 ngFor 指令动态添加的 HTML 表中恢复标题单元格数据

问题描述

我正在尝试从我的 typescript .ts 文件中的数组标题中检索单元格数据。知道这些单元格是使用指令<th>动态生成的。ngFor我只得到用硬(action、a、b、c、d)编写的列名,而不是从我的 API 动态生成的其他名称。我想检索动态生成的列名。

这是我的 HTML 文件:

<table class="table table-striped">
  <thead id="thead">
    <tr id="head">
      <th class="columnName">Action</th>
      <th class="columnName">a</th>
      <th class="columnName">b</th>
      <th class="columnName">c</th>
      <th class="columnName">d</th>
      <th scope="col" *ngFor="let column of table.columns" class="columnName">{{ column.name }}</th>
    </tr>
  </thead>
</table>

这是我的 component.ts 文件

getColumnName() {
    const theadRow = document.getElementsByClassName('columnName');
    // const thList = theadRow.children;
    console.log(theadRow);

    for (let i = 0; i < 23; i++) {
      console.log(theadRow[i].innerHTML);
    }

这是我的结果: 在此处输入图像描述

标签: javascriptangular

解决方案


您可以调用var names = table.columns.map(col => col.name)以提取名称。

这是有关Array.map()的更多信息


推荐阅读