Home > Enterprise >  how to initialize FormGroup when the FormControlName is dynamic and can be changed?
how to initialize FormGroup when the FormControlName is dynamic and can be changed?

Time:07-21

I'm new to angular and I'm facing this case .

in my HTML page a form (formgroup) and inside it i have a div with ngFor directive to loop through an object for whatever time as much needed.

say that I have an input field with formControlName like this :

<input type="text" formControlName="name{{i}}" >

how will I create the FormGroup object in the typescript file ???

In normal case when the controlName is not dynamic I used to do something like this :

this.namedForm = new FormGroup({
   'name': new formControl(),
});

and it works ok ,

but when I add the index to the formControlName how would I create the formGroup object ?

I tried something like this but it is showing error...

let nameControl = 'name' i;
this.namedForm = new FormGroup({
   nameControl : new formControl(),
});

any help ?

CodePudding user response:

You need add control dynamically like

this.namedForm.addControl(this.name, new FormControl(''));

See this example: https://angular-ivy-9rbeic.stackblitz.io

CodePudding user response:

Well, the object that you loop through with the ngFor will somehow be initialized/changed at some point. (For instance, if your object is an input as it seems to be what you want to do, you can detect its changes in the ngOnChanges hook.)

Then everytime you initialize or change your object, you just need to initialize your FormGroup again, with the correct TControl collection built depending on what is the new value of your object. For instance:

myNgForObjectForHasBeenChanged(objectUpdated:any){
  let controls:TControl = {};
  
  for(let objectIndex in objectUpdated){
    //Or use 'name' index or whatever, instead of objectIndex
    //what is important is that your "controls" collection needs unique indexes
    controls[objectIndex] = new FormControl();
  }
  
  this.namedForm = new FormGroup(controls);
}

CodePudding user response:

You can use FormArray to handle array values in forms.

new FormGroup({
  textContainer: new FormArray([
    new FormControl('')
  ])
});

And the template could be like:

<ul formArrayName="textContainer">
  <li *ngFor="let item of form.controls.textContainer.controls; let i = index">
    <input type="text" formControlName="{{i}}">
  </li>
</ul>

See also: https://angular.io/api/forms/FormArrayName

  • Related