【问题标题】:Dynamically add row to table in Angular在Angular中动态地将行添加到表中
【发布时间】:2019-05-02 21:48:54
【问题描述】:

我有一张表,想动态地向该表中添加一行。下面是我的代码!

<tr *ngIf="customer">
  <td>4</td>
  <td>
    <input type="text" name="firstName" required minlength="2">
  </td>
  <td>
    <input type="text" name="lastName" required minlength="2">
  </td>
  <td>
    <input type="text" name="countryCode" required maxlength="2">
  </td>
  <td>
    <input type="number" name="age" required minlength="2">
  </td>
  <td>
    <i class="fas fa-times" (click)="cancel()"></i>
  </td>
  <td>
    <i class="far fa-save" (click)="save()"></i>
  </td>
</tr>

应在表格下方添加上面的行。是保存上述 html 的选择器(要添加的单个表格行)。目前,当单击按钮时,上面的行显示在页面的最底部,而不是按预期添加到表格中。

<table class="table">
        <thead>
          <tr>
            <th scope="col">#</th>
            <th scope="col">First</th>
            <th scope="col">Last</th>
            <th scope="col">Country</th>
            <th scope="col">Gender</th>
            <th scope="col">Age</th>
            <th scope="col">Edit</th>
            <th scope="col">Delete</th>
          </tr>
        </thead>
        <tbody>
          <tr *ngFor="let customer of customerArray; let i = index">
            <td>{{i + 1}}</td>
            <td>{{customer.firstName}}</td>
            <td>{{customer.lastName}}</td>
            <td>{{customer.countryCode}}</td>
            <td>{{customer.gender}}</td>
            <td>{{customer.age}}</td>
            <td><i class="fas fa-edit" (click)="editCustomer()"></i></td>
            <td><i class="fas fa-trash-alt" (click)="deleteCustomer(customer)"></i></td>
          </tr>
          <add-edit-customer></add-edit-customer>
        </tbody>
      </table>

【问题讨论】:

  • 只是将新客户推入cutomerArray 应该添加新行吗?
  • 如果您使用查看源代码功能或开发人员工具元素选项卡,您将看到由您的视图生成的 HTML。您会注意到嵌套元素 (add-edit-customer) 会干扰表格的布局。最好的办法是按照此处提供的建议添加到您的 customerArray

标签: angular html-table


【解决方案1】:

Angular 是一个框架,其主要目的是在模型更改时更新视图。模板代表了一种简单的方法来“教”Angular 在模型发生更改时如何更新实际的 DOM(在应用程序运行时)。

您的行是通过读取customerArray 来呈现的。

<tr *ngFor="let customer of customerArray; let i = index">

要添加另一行,只需将另一个对象添加到customerArray,Angular 将自行处理更新视图。

【讨论】:

  • 但这就是我正在做的! 在单击创建客户对象的按钮时被激活,并且还会创建表格行。我的问题是,创建的相应行没有添加到 (这是表所在的位置)组件,而是一直添加到它的末尾。所以我希望能够将行动态添加到该表中,作为 HTML DOM 中该表的一部分,有点像将一行(在一个组件“add-edit-customer”中)注入到表中(在另一个组件“所有客户”)。
【解决方案2】:

来自Angular2 : render a component without its wrapping tag

如果你想在表格中添加一个 tr 你的组件可以像

@Component({
  selector: '[add-edit-customer]',  //<--see you enclosed the name by []
  template: `<td><input ...></td>  //see you don't include tr tag
             <td><input ...></td>`
})

还有你的 .html

<tbody>
   <tr *ngFor="let customer of customerArray; let i = index">
      <td>{{i + 1}}</td>
      ...
   </tr>
   <!-- see that add-edit-customer is a especial "tr"-->
   <tr add-edit-customer></tr>
</tbody>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-30
    • 2019-05-19
    • 1970-01-01
    相关资源
    最近更新 更多