【问题标题】:How do I insert anchor tag dynamically in the cell of a table using typescript?如何使用打字稿在表格的单元格中动态插入锚标记?
【发布时间】:2021-12-15 23:38:28
【问题描述】:

我正在尝试在我使用打字稿动态创建的 HTML 表中插入一个工作锚标记作为链接,但是当我使用 innerHTML 添加锚标记并将其附加到单元格时,该表仅显示文本锚标记和链接不起作用。我附上了打字稿、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>

前端截图。

如何使用 typescript 将工作锚标记动态添加到 HTML 表格的单元格元素?

【问题讨论】:

  • 请将您的代码添加为文本,图片使您更难找到此问题:meta.stackoverflow.com/questions/285551/…
  • 您在 javascript 中创建 html 而不是使用 Angular 模板引擎是否有特定原因?
  • 你确定你使用的是 AngularJS 而不是 angular?
  • 我正在使用 Angular
  • 如果你能建议我做同样事情的另一种方法,那会很有帮助,我是 Angular 新手

标签: html angular typescript html-table anchor


【解决方案1】:

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

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 轻松添加更多组件。

【讨论】:

  • 非常感谢,这解决了我的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-17
  • 1970-01-01
相关资源
最近更新 更多