如何动态创建多个输入,然后可以在Angular 2中获取它们的值?

Hon*_*iao 7 angular

我正在使用Angular 2.

我想动态创建多个输入,然后提供通过使用[(ngModel)]="input1"或其他方式获取其值的方法:

我考虑过使用[hidden],但由于我不知道用户想要的确切输入数量,所以我询问了如何动态创建输入.

HTML

<button (click)="addInput()">Add Input</button>
Run Code Online (Sandbox Code Playgroud)

TS

addInput() {
    // first time click, add <input type="text" [(ngModel)]="input1"/>
    // second time click, add <input type="text" [(ngModel)]="input2"/>
    // third time click, add <input type="text" [(ngModel)]="input3"/>
    // forth, fifth, etc.
}
Run Code Online (Sandbox Code Playgroud)

谢谢

Mar*_*cok 9

创建一个对象数组.如果需要新输入,请按下阵列.使用NgFor生成的表单元素.

@Component({
  selector: 'my-app',
  template: `<button (click)="addInput()">Add Input</button>
  <div *ngFor="let input of inputs">
    <input [(ngModel)]="input.value">
  </div>
  {{inputs | json}}`
})
export class AppComponent {
  inputs = [{value: "first"}];
  addInput()  {
    this.inputs.push({value: ''});
  }
}
Run Code Online (Sandbox Code Playgroud)

Plunker