Search code examples
angularangular-reactive-formsformarraymat-select

How to set default value for mat-select with reactive form is used


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?


Solution

  • 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