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
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
You can use addControl on your Form object:
this.yourForm.addControl("inputName", new Control);
https://plnkr.co/edit/MahOzQqkyv613N1NtElF?p=preview
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With