0

I have used reactive forms for creating a dynamic filter form. I want to set the default value for mat-select. Codes are as follows:

component.html:

<form [formGroup]="filterForm" (ngSubmit)="onSubmit()">
    <div class="to-create" formArrayName="filters">
        <div class="sub-items" *ngFor="let child of filters().controls; let i = index" [formGroupName]="i">
.
.
.
            <mat-form-field class="form-field column-select" appearance="outline">
                <mat-select formControlName="columnName">
                    <mat-option *ngFor="let column of columnList" [value]="column">
                        {{column}}
                    </mat-option>
                </mat-select>
            </mat-form-field>
.
.
.
        </div>
    </div>
</form>

component.ts

columnList = ['C1', 'C2', 'C3', 'C4'];

ngOnInit(): void {
  const columnListDefault = this.columnList[0];

  this.filterForm.get('columnName')?.setValue(columnListDefault );
}

But it does not work and the default value is empty. I studied some related threads such as:

How can I fix it?

Yong Shun
  • 35,286
  • 4
  • 24
  • 46
Alex Wright
  • 421
  • 1
  • 11
  • Did you define your filterForm as a `FormGroup`? If so you could try to set the value like this: `this.filterForm.setValue({columnName: this.columnList[0]});` – binbash Oct 12 '22 at 08:31

1 Answers1

1

Your form structure is:

filterForm (root FormGroup) --> filters (FormArray) --> index (FormGroup) --> columnName (FormControl)

Hence your statement to set the default value for columnName FormControl is incorrect.


You have to iterate the FormGroup in filters FormArray in order to assign the value to columnName FormControl.

To set the value to columnName control of first FormGroup in filters FormArray:

this.filters().get('0').get('columnName').setValue(columnListDefault);

To set the value to columnName control of each FormGroup in filters FormArray:

for (let index in this.filters().controls) {
  (this.filters().get(index) as FormGroup)
    .get('columnName')
    .setValue(columnListDefault);
}

Demo @ StackBlitz

Yong Shun
  • 35,286
  • 4
  • 24
  • 46