Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically create multiple inputs and then can get their values in Angular 2?

Tags:

angular

I am using Angular 2.

I want to dynamically create multiple inputs, and then provide ways to get their value by using [(ngModel)]="input1" or other ways:

I thought about using [hidden], but since I don't know the exact number of inputs the user wants, so I asked about how I can dynamically create inputs.

html

<button (click)="addInput()">Add Input</button>

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.
}

Thanks

like image 331
Hongbo Miao Avatar asked Feb 13 '16 22:02

Hongbo Miao


2 Answers

Create an array of objects. Push onto the array when you want a new input. Use NgFor to generate the form elements.

@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: ''});
  }
}

Plunker

like image 83
Mark Rajcok Avatar answered Nov 10 '22 01:11

Mark Rajcok


You can use addControl on your Form object:

this.yourForm.addControl("inputName", new Control);

https://plnkr.co/edit/MahOzQqkyv613N1NtElF?p=preview

like image 31
Vlado Tesanovic Avatar answered Nov 10 '22 00:11

Vlado Tesanovic