如何使用打字稿在 table 的单元格中动态插入锚标记?

How do I insert anchor tag dynamically in the cell of a table using typescript?

我正在尝试在 HTML table 中插入一个工作锚标记作为 link 我正在使用打字稿动态创建,但是当我使用 inner 添加锚标记时HTML 并将其附加到单元格,table 仅显示锚标记的文本而 link 不显示 work.I 我附上打字稿的屏幕截图,html 和前端。

TypeScript 函数

populateList(){
let table = document.querySelector("table");
let data=["Sr.No","Exam Name","Link to Exam"];
let thead = table!.createTHead();
let row = table!.insertRow();
  for (const key of data) {
    let th = document.createElement("th");
    let text = document.createTextNode(key);
    th.appendChild(text);
    row.appendChild(th);
  }

// var tablebody:string=``
// var output:any=[];
// var tablerow:any=[];
// var tableend=``
this.myData.forEach((currentExam:any,examNumber:any) => {
  var htmlVariable=`<a [routerLink]="['session']" [queryParams]="{id:'${currentExam.id}'}">Start Exam</a>`
  let row=table!.insertRow();
  let cell = row!.insertCell();
  let text = document.createTextNode(`${examNumber}`)
  cell.appendChild(text);
  cell=row.insertCell();
  text=document.createTextNode(`${currentExam.examName}`);
  cell.appendChild(text);
  cell=row.insertCell();
  var content=document.createElement("div");
  content.innerHTML=htmlVariable;
  cell.appendChild(content);
});

HTML代码

<html>
<head>
    <title>Student Homepage</title>
</head>
<body>
    <h1 align="center">Welcome to Student Homepage.</h1>
    <table class="center">
    </table>
    <div id="container"></div>
</body>

前端截图。

如何使用打字稿将有效的锚标记动态添加到 HTML table 的单元格元素?

您可以使用以下设置动态构建 table:

students.component.ts

@Component({
  selector: "app-students",
  templateUrl: "./students.component.html",
  styleUrls: ["./students.component.css"]
})
export class StudentsComponent {
  tableColumnLabels = ["Sr.No", "Exam Name", "Link to Exam"];

  exams = [
    { id: "1", name: "first Exam" },
    { id: "2", name: "second Exam" }
  ];
}

students.component.html

<table>
  <th *ngFor="let columnLabel of tableColumnLabels">{{ columnLabel }}</th>
  <tr *ngFor="let exam of exams; index as examNumber;">
    <td>{{ examNumber }}</td>
    <td>{{ exam.name }}</td>
    <td>
      <a [routerLink]="['session']" [queryParams]="{id: exam.id}">Start Exam</a>
    </td>
  </tr>
</table>

您可以使用 ng generate component MyComponent 轻松添加更多组件。