0

So far, I've written below code

<form [formGroup]="testForm">
    <div formArrayName="selects">
        <mat-form-field *ngFor="let select of selects.controls; let i = index">
            <mat-select [formControlName]="i">
                <mat-option *ngFor="let option of select.value.options" [value]="option">{{ option }}</mat-option>
            </mat-select>
        </mat-form-field>
    </div>
</form>

In the component file

testForm: FormGroup;

get selects() {
  return this.testForm.get('selects') as FormArray;
}

data = [{
  initial: 'one',
  options: ['two', 'three', 'four']
}, {
  initial: 'a',
  options: ['b', 'c', 'd']
}];

constructor(private formBuilder: FormBuilder) { }

ngOnInit() {
  this.testForm = this.formBuilder.group({
    selects: this.formBuilder.array([]),
  });

  for (let i = 0; i < this.data.length; i++) {
    this.selects.push(new FormControl(this.data[i]));
  }
}

But this is not working so far. What I am doing wrong here?

Find the Stackblitz here.

Issue: As you can see in the stackblitz, it is not showing the initial value and if we select the option, then also it is not working and also options are disappearing from the select if we select any option.

2
  • Can you please clarify what exactly doesn't work? Commented Aug 25, 2019 at 13:44
  • Hi @yurzui as you can see in the stackblitz, it is not showing the initial value and if we select the option, then also it is not working and also options are disappearing Commented Aug 25, 2019 at 13:48

1 Answer 1

2

Your example looks strange:

{
  initial: 'one', <------------  it is not in options array
  options: ['two', 'three', 'four']
}

But anyway if you want to make it work with FormArray then you should be mapping initial value and not the whole object:

this.testForm = this.formBuilder.group({
  selects: this.formBuilder.array(this.data.map(item => new FormControl(item.initial))),
});

And your html should look like:

<mat-form-field *ngFor="let select of data; let i = index">
    <mat-select [formControlName]="i">
        <mat-option *ngFor="let option of select.options" [value]="option">{{ option }}</mat-option>
    </mat-select>
</mat-form-field>

As you can see I loop over original data array.

Forked Stackblitz

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah, that's true, I missed it :-). I am trying your solution in my original code. I have one doubt, instead of using data to loop, can't we use selects.controls
We can use selects.controls but we need to get options somehow. We don't keep options in FormArray. Now it's only array of FormControl's. I use loop over data because I have select.options access

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.