Search code examples
angulardynamic-variables

Export NgForm to Local Dynamic Variable in Angular 2


I'm beginner in Angular 2/4. In my sample project, I trying to find out how to place multiple forms inside a for loop and associate each form with a dynamic variable. I had gone through multiple documentations and know that form can be associated with single static variable (#f) as:

<div *ngFor="let item of Collection; let i = index" #f="ngForm">

But i could not find anyway to create the variable dynamically, for ex.

<div *ngFor="let item of Collection; let i = index" #f{{i}}="ngForm">

Solution

  • If you are using Model Driven Forms, I suggest you use FormArray, it will make your life a lot easy.

    https://plnkr.co/edit/clTbNP7MHBbBbrUp20vr?p=preview

         <div formArrayName="addresses">
              <div *ngFor="let address of myForm.controls.addresses.controls; let i=index" class="panel panel-default">
                <div class="panel-heading">
                  <span>Address {{i + 1}}</span>
                  <span class="glyphicon glyphicon-remove pull-right" *ngIf="myForm.controls.addresses.controls.length > 1" (click)="removeAddress(i)"></span>
                </div>
                <div class="panel-body" [formGroupName]="i">
                  <address [group]="myForm.controls.addresses.controls[i]"></address>
                </div>
              </div>
            </div>
    

    In this example you can add as many address you want, which are basically a group of FormGroup

    Check :
    https://angular.io/api/forms/FormArray
    and:
    https://scotch.io/tutorials/how-to-build-nested-model-driven-forms-in-angular-2