0
votes

I have the following form dinamically populated with multiple select inputs

<form [formGroup]="searchForm" (ngSubmit)="onSubmit(searchForm.value)">
   <div class="col-md-2" *ngFor="let filter of this.filters; index as i">
      <div class="form-group">
        <select formArrayName="filters" size="5" class="form-control" (change)="onSelectChange($event)">
          <option [ngValue]="null" value="-1" disabled class="first-option-item">{{ filter.name }}</option>
          <option
            *ngFor="let filterValue of this.filterValues[i].items"
            [ngValue]="filterValue">
              {{ filterValue.name }}
          </option>
        </select>
      </div>
    </div>
</form>

Reactive form init:

this.searchForm = this.formBuilder.group({
  searchString: ['', Validators.required],
  filters: this.formBuilder.array([ ])
});

However I don't have any values on the filter array when I submit the form

enter image description here

Furthermore, when I log e.target.value on my (change) method I only get the selected option value. I want to access the full object i.e { id: 1, name: 'first_filter' }. Don't I need the full object so I can return it somehow to the FormGroup?

1
Can you show how the filters are being addedKurt Hamilton
this.preferencesService.getAllFilters().subscribe((res: any) => { this.filters = res.filters; this.filterValues = res.filter_items;})shAkur

1 Answers

0
votes

Your problem

You are building an array of selects in a form. When you submit the form, the select values aren't set.

The design

When binding to form arrays, you bind the array to formArrayName, and each control in the array to [formControlName]="i".

The solution

Move formArrayName="filters" to a higher level, and add [formControlName]="i" to the select. This will bind the ith select to the ith control in the form array.

I've also amended your [ngValue]="filterValue" to use filterValue.name for the purposes of my example.

<form [formGroup]="searchForm" (ngSubmit)="onSubmit()">
  <div class="col-md-2" *ngFor="let filter of this.filters; index as i"
    formArrayName="filters">
    <div class="form-group">
      <select [formControlName]="i" size="5" class="form-control" (change)="onSelectChange($event)">
        <option [ngValue]="null" value="-1" disabled class="first-option-item">{{ filter.name }}</option>
        <option
          *ngFor="let filterValue of this.filterValues[i].items"
          [ngValue]="filterValue.name">
            {{ filterValue.name }}
        </option>
      </select>
    </div>
  </div>
  <button>Submit</button>
</form>

DEMO: https://stackblitz.com/edit/angular-i3njdo