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 formArrayName="filters">
<div *ngFor="let child of filters().controls; let i = index" [formGroupName]="i">
.
.
.
<mat-form-field 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:
- Angular Material: mat-select default value when using reactive forms
- Set default option in mat-select
How can I fix it?
CodePudding user response:
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);
}
