【问题标题】:Get Data from Dynamically Created textboxes in Angular using ng-for使用 ng-for 从 Angular 中动态创建的文本框中获取数据
【发布时间】:2020-09-23 15:24:43
【问题描述】:

我已经创建了一组像这样动态创建的文本框


  <input id="Pun{{item}}" type="text" 
    class="form-control textbox" placeholder=Punishment >

</div>

其中的惩罚数字是一个数字数组。我想知道如何从每个创建的文本框中获取数据,不胜感激。

【问题讨论】:

  • 我们使用 `[(ngModel)] 绑定到每个输入
  • 我尝试这样做,但它使所有文本在其他文本框中重复。
  • 尝试使用带有trackby函数的ngfor

标签: javascript html angular typescript


【解决方案1】:

我在stackblitz 上创建了一个解决方案。

使用*ngFor 迭代的值更新每个输入的值,如下所示。

<div *ngFor="let item of items">
  <input id="Pun{{item}}" type="text" [(ngModel)]="pun[item]" 
    name="pun[item]" class="form-control textbox" placeholder="punishment 
  {{item}}" > {{pun}}
</div>

在哪里

items = [1, 2, 3, 4];
pun = [];

【讨论】:

  • 我已经改进了你的答案,但请花点时间阅读How to Answer
【解决方案2】:

您可以使用 document.getElementById()。

您的 HTML 文件:

  <input id="Pun{{item}}" type="text" class="form-control textbox" placeholder=Punishment>

你的 ts 文件:

 var item="YOUR_ITEM_HERE";
 var textValue = (document.getElementById("Pun"+item) as any).value;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-13
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多