0

I need to create a form to register the partners of a company.

There is a checkbox, that when it is checked 1 field is enable and you can insert the information, for ex: -> name of partner.

But if the user wants to register more the 1 partner, could be a button that create another field to insert other name.

How can I work with this name fields? When I used PHP, I put the field like this:

And I get the values = name[0] ... name[1] ...etc

In Angular 2, how can I do this?

  • And what have you tried? This is not a free coding service ;) – AT82 Mar 06 '17 at 19:02
  • I’m asking ideas about how can I do this in Angular 2, but if you don’t want to answer, please don’t disturb ;D – Fernando Herique Rubim Pioli Mar 06 '17 at 20:09
  • :P Well, create an array, iterate it with ngFor and display an input field inside the iteration, and on click of button add a new item to your array. Check the tutorials at angular.io that's a good tutorial for getting the hang of basics :) – AT82 Mar 06 '17 at 20:15
  • I found a nice information about this: [link of a answer](http://stackoverflow.com/questions/38007236/how-to-dynamically-add-and-remove-form-fields-in-angular-2) – Fernando Herique Rubim Pioli Mar 07 '17 at 20:10
  • Aah, missed that you wanted a form, well yes, there are plenty of good answers for that. And depending on the route you want to go, you can choose dynamic (like the answer) or template driven forms. You can read about these also at angular.io and there are several other good links out there with searchwords "dynamic form angular 2" or "template driven form angular 2" :) But good that you found a good example, happy coding and come back if you encounter problems, but let's hope you dont! ;) – AT82 Mar 07 '17 at 20:19
  • Yes, I didn't find because I didn't know the name: Nested Model-driven Forms in Angular 2 ... When I knew this, It was easy ... I'm working on this... Thanks for your attention. – Fernando Herique Rubim Pioli Mar 07 '17 at 20:24

1 Answers1

1

you can create an array like

let fields: any = [{
 checkbox: false,
 textbox: ""
}];

use loop through the form elements using this array like this

<div *ngFor="let item of fields;">
 <input type="checkbox" name="somename" [(ngModel)]="item.checkbox"/>
 <input type="text" [disabled]="item.checkbox" name="somename" [(ngModel)]="item.textbox"/>
</div>
<button (click)="addField()">Add Another</button>

whenever user click on this button

addField(){
 this.fields.push({
  checkbox: false,
  textbox: ""
 });
}

thats it

Babar Hussain
  • 2,917
  • 1
  • 17
  • 14