Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form input arrays in angular

I am learning Angular.js and i've come to a problem that should probably be simple, but I can't seem to find an answer on.

I want to create form inputs with the value of "connectedTeams", like this in html:

<input type="text" name="connectedTeam[]"> 
<input type="text" name="connectedTeam[]"> 
<input type="text" name="connectedTeam[]"> 

I have tried the following in angular...

<input type="text" name="connectedTeams[]" class="form-control" ng-model="user.connectedTeams">

...but it is binding the same value to all 3 inputs. I know in my mind that this makes sense, but I can't seem to figure out how to tell it that ng-model is user.connectedTeams.[] (user > connectedTeams > add to an array.

I hope this makes sense enough for someone to provide a quick answer.

like image 572
Daniel White Avatar asked Jan 26 '15 16:01

Daniel White


People also ask

What is form array in angular?

A FormArray aggregates the values of each child FormControl into an array. It calculates its status by reducing the status values of its children. For example, if one of the controls in a FormArray is invalid, the entire array becomes invalid.

How do you create FormArray in angular 12?

First, we need to import the FormArray from the Angular Forms Module. Build a formGroup orderForm using the FormBuilder. We define items as FormArray. We need to capture two fields under each item, the name of the item & description and price.

Can a form control be an array?

Actually, a FormArray can have an undetermined number of form controls, starting at zero! The controls can then be dynamically added and removed depending on how the user interacts with the UI. Each control will then have a numeric position in the form controls array, instead of a unique name.

How do I create an empty array form?

You can manually clear each FormArray element by calling the removeAt(i) function in a loop.


1 Answers

 ng-model="user.connectedTeams[0]"
 ng-model="user.connectedTeams[1]" and so on

You can put it in a ngRepeat, so you don't need to repeat your code like above.

FYI, name is only used for validation in Angularjs.

like image 56
maxisam Avatar answered Oct 02 '22 03:10

maxisam