0

I have a form, and this form includes a field with two buttons +/- next to it, so the user can add or remove fields of this kind (up to five).

I have a var count in the typescript to keep track of how many fields of this kind I have.

And depending on this number, I need to display the same part of the form as many times as there are fields, and dynamically.

How can I do this?

I can't find a way in Angular to repeat the same HTML block depending on a variable, and I can't code all the blocks and use ngIf as the HTML block is huge.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
Manon Ingrassia
  • 270
  • 3
  • 14
  • Please include the actual code instead of a description of the code in your question. This might be helpful: [how to create a minimal, verifiable example](https://stackoverflow.com/help/mcve). Good luck! – kenny_k Jan 18 '18 at 12:55

2 Answers2

0
  • You can use reactive forms in angular. Build a formarray using the form builder.
  • Push and pop the form controls into the formarray whenever the + and - buttons are clicked using the methods available on the formarray Class
  • The same will be reflected in the view as it is done on a click event which the angular change detection can take care of.
  • In the click event handler method handle the condition to limit the form controls you push to 5 based on the length of the formarray.
  • In the template use the formArrayName directive on a div and inside it use ngFor to loop through the controls in the formarray and put the html you like to loop inside it along with the [formControl] directive on the form field
web-master
  • 716
  • 7
  • 12
  • Thanks, it seems good, but I am wondering just one thing: all examples I saw on internet used formarray of formcontrols. That's alright when you have to repeat just one field, but as I have to repeat a block of several fields here how should I do? I can only think of an array of array, but this is definitely not the best option – Manon Ingrassia Jan 19 '18 at 08:17
  • Nevermind, I found out about nested model-driven form while searching informations about formarray, and it looks like this is exactly what I need. Here is the link, for those who have the same problem: https://scotch.io/tutorials/how-to-build-nested-model-driven-forms-in-angular-2 – Manon Ingrassia Jan 19 '18 at 08:46
  • nested form arrays are possible in reactive forms also - https://stackoverflow.com/questions/42783400/nested-arrays-in-angular-2-reactive-forms – web-master Jan 20 '18 at 11:21
0

Just create an array, which will contain an element for each div that you add, creating a function like:

addDiv(){
    if(this.divs.length<5){
        this.divs.push({id:this.divs.length});
    }
}

And then, on the template, iterate over it with:

<div *ngFor="let element of divs">
</div>
Birrask
  • 1
  • 1