【问题标题】:How to dynamically add HTML element/content - Angular如何动态添加 HTML 元素/内容 - Angular
【发布时间】:2019-02-18 07:42:02
【问题描述】:

动态添加 HTML 元素(例如在基本 HTML 表格中添加另一列)的最佳方式是什么?

我希望在表格下方有一个按钮,如果用户单击该按钮,该事件将在表格中添加相同数量的行并添加另一列。我希望支持将大约 5 个额外的列添加到表中。

这是我现在的 HTML 表格:

<table>
<thead>
    <tr>
        <th id="row-tag"></th>
        <th id="option-column">Option 1</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td id="row-tag">P</td>
        <td id="option-column">{{ p }}</td>
    </tr>
    <tr id="row-tag">
        <td>
            <app-a-p (saveButtonClick)="toggleAP($event)"
                                  [modModalValues]="modModalValues">
            </app-a-p>
        </td>
        <td id="option-column">
            <div class="input-group input-group-sm">
            $<input
                   *ngIf="toggleAP==true"
                    type="text"
                    name="aP"
                    size="10"
                    disabled
                    value=""
                    />
            <input
                   *ngIf="toggleAP==false"
                    type="text"
                    name="aP"
                    size="10"
                    [ngModel]="con.pA"
                    (ngModelChange)="con.pA = $event" appFormatP
                    (blur)="checkAP($event.target.value);
                            inputTracker.addModifiedValue('Option 1', $event.target.value)"
                    />

            </div>

        </td>
    </tr>
    <tr>
        <td id="row-tag">L</td>
        <td id="option-column">${{l}}</td>
    </tr>
    <tr>
        <td id="row-tag">R</td>
        <td id="option-column">${{r}}</td>
    </tr>
</tbody>
</table>

【问题讨论】:

    标签: html angular typescript dynamic


    【解决方案1】:

    我认为在 Angular 中,您可以根据数据定义表格。例如,您有 fields 数组定义列,而 data 数组定义表中的实际内容。

     <table >
          <thead>
          <tr>
            <th  *ngFor='let key of this.fields'>{{key}}</th>
          </tr>
          </thead>
          <tbody>
          <tr  *ngFor='let row of this.data ' >
            <td scope="row"  *ngFor='let key of this.fields'> {{row[key]}} </td>
          </tr>
          </tbody>
        </table>
    

    当您需要新列时,只需将新字段推入字段即可。喜欢

       fields.push('newcolumn');
    

    当您需要新行时,只需执行以下操作:

      data.push({col1: '', col2:'', newcolumn: ''});     
    

    【讨论】:

      【解决方案2】:

      查看 JavaScript 中的 insertRow()insertCell() 函数。这与您编写的 onClick 函数一起可以让您编辑表格。

      【讨论】:

      • 我会调查的。谢谢。
      【解决方案3】:

      在使用 Angular 时在 UI 上生成表格的一种好方法是使用 2D 数组(行*列)使用可以有一个按钮,您可以使用该按钮向该数组动态添加值,并在该数组中添加另一行/列桌子。

      【讨论】:

      • 我会调查的。有没有你知道的例子?
      猜你喜欢
      • 1970-01-01
      • 2022-01-02
      • 2016-07-09
      • 1970-01-01
      • 2012-04-18
      • 1970-01-01
      • 2019-02-22
      • 2019-01-06
      • 1970-01-01
      相关资源
      最近更新 更多