0
this.formgroup = formbuilder.group({
      os: [null, [Validators.required]],
});

const osType= ['Android', 'Ios']

I tried

this.formgroup.controls.os.setValue(osType)

Result

os: ['Android', 'Ios']

Expected Result

os: 'Android'
os: 'Ios'

I need to send data from using formdata. i have tried with setValue but i got different result than i expect. can someone tell me how to do for the expected result. Thank in advance

Benni
  • 15
  • 5
  • You need to create Array of FormGroup, May be this will help https://stackoverflow.com/questions/41288928/when-to-use-formgroup-vs-formarray – Chellappan வ Oct 15 '20 at 04:49

1 Answers1

0

you need a FormArray of FormControls. Typicall you transform the array in FormControls using map

this.formarray = this.formbuilder.array(
    this.osType.map(x=>this.formbuilder.control(x))
);

See stackblitz

If you want to use setValue, remember that the formArray must be the same number of elements that the array before use setValue

NOTE: if you want to manage a formArray that is NOT inside a formGroup you need create an auxiliar function

  getControl(i)
  {
    return this.formarray.at(i) as FormControl
  }

Then you can write

<div *ngFor="let control of formarray.controls;let i=index">
    <input [formControl]="getControl(i)">
</div>

NOTE 2: Before Angular 10 you can make in others ways: using the formArray like a formGroup or using the variable of the loop to indicate the control, but nowadays this is the way to control a formArray "standalone"

Eliseo
  • 50,109
  • 4
  • 29
  • 67