Reputation: 11
I need to repeat a form on click of a link in angular2 how would i do that?
for example if i have a form to add a person name and age when i click on "addnewperoson" i want to get the same form added just below the previous form any suggestions would be helpful need immediate reply
something like this in this link http://www.shanidkv.com/blog/angularjs-adding-form-fields-dynamically
Upvotes: 1
Views: 2337
Reputation: 2494
You can create empty array then on click add something in that array, in html you loop thru that array. Add user will create new elements with button for removing individual by index.
For example.
.ts
users: any[] = [];
addUser(){
this.users.push({});//push empty object of type user
}
removeUser(i){
this.users.splice(i, 1);
}
.html
<a (click)="addUser()">Add User</a>
<div *ngFor="let user of users; let i = index">
<label>Name</label>
<input [(ngModel)]="user.name" name="name">
<label>Age</label>
<input [(ngModel)]="user.age" name="age">
<a (click)="removeUser(i)">Remove</a>
</div>
Upvotes: 3
Reputation: 2137
In your component you can create an array of objects as in you link example (I would also added fields into this objects which also might be objects - depends on your needs):
[
{ id: "choice1", fields: ["name", "age"]},
{ id: "choice2", fields: ["name", "age"]},
{ id: "choice3", fields: ["name", "age"]}
]
and in template show your forms with *ngFor
.
Then push { id: "choiceN", fields: ["name", "age"]}
to this array on button click
Upvotes: 0