Angular 6-如何使用* ngFor从表中动态创建的输入框中获取component.ts中的输入值?

时间:2018-08-03 10:38:49

标签: angular6

在以下情况下,我需要帮助:假设我们为以下HTML创建了10行,那么如何获取所有10行在FORM SUBMIT上以角度6插入所有的名字和姓氏值?

<form name="userForm">
<table>
<tr *ngFor="let item of itemList; let in = index">
      <td><input type="text" name="lastname-{{in}}" [(ngModel)]="item.lastname"></td>
      <td><input type="text" name="middlename-{{in}}" [(ngModel)]="item.middlename"></td></tr></table></form>

1 个答案:

答案 0 :(得分:1)

您可以在提交表单时使用itemList

<form name="userForm">
    <table>
        <tr *ngFor="let item of itemList; let in = index">
            <td><input type="text" name="lastname-{{in}}" [(ngModel)]="item.lastname">
            </td>
            <td><input type="text" name="middlename-{{in}}" [(ngModel)]="item.middlename">
            </td>
        </tr>
        <input type="button" (click)="onSubmit()" value="submit">
    </table>
</form>
<pre>
  {{this.itemList | json}}
</pre>

还有ts代码。

      itemList = [{
        lastname: "",
        middlename: ""
      },
      {
        lastname: "",
        middlename: ""
      },
      {
        lastname: "",
        middlename: ""
      }]

      constructor() { }

      onSubmit() {
        console.log(JSON.stringify(this.itemList));
      }