Waleed Shahzaib
Waleed Shahzaib

Reputation: 1716

Issue in adding a control dynamically to a reactive form in Angular

I am working on Angular Reactive forms. I want to add controls dynamically to form. But when I add a control it added twice at first time I don't know why, afterward it works fine. here is the code:

<form [formGroup]="reviewForm" >        
    <span *ngIf="isClicked">              
        <div formArrayName="controlArray">
            <div 
              class="form-group"
              *ngFor="let control of reviewForm.get('controlArray').controls; let i = index">            
              <label>{{label}} </label>                                      
              <input 
                type="{{control.value}}"                       
                class="form-control"                                        
                [formControlName]="i" >                       
            </div>  
        </div>  
    </span>
    <button type="button" (click)="addControl()">Add</button>         
</form>

component class code, addControl() is invoked on Add button click event:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormArray, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {  
  reviewForm: FormGroup;
  inputArray: string[] = [
    'text', 'radio', 'checkbox', 'select', 'textarea', 'button'
  ];

  selectedControl: string = '';   
  isClicked:boolean= false;
  label: string;
  isRequired:boolean = false;
  placeHolderValue: string = "";
  ngOnInit(){
    this.reviewForm = new FormGroup({   
      // 'placeHolder' : new FormControl(null),   
      'controlArray': new FormArray([
        new FormControl(null)
    ])
    });
  }

  addControl(){    
      this.isClicked = true;
      const control = new FormControl(this.selectedControl);
      (<FormArray>this.reviewForm.get('controlArray')).push(control);      
      // console.log(this.selectedControl);      
    }  

  onSubmit(){
    console.log(this.reviewForm);
  }
}

Upvotes: 1

Views: 983

Answers (1)

Mohamed Ali RACHID
Mohamed Ali RACHID

Reputation: 3297

what happens is very normal , because when ur componenet is created , isClicked = false and your formArray contains already one FormControl that is not shown in the beginning because of this condition : <span *ngIf="isClicked">

when you add a new Control to the FormArray , now it contains two FormControls and isClicked becomes true , and two formControl are shown.

this the reason of this behavior

Hope it helps :)

Upvotes: 2

Related Questions