What is the optimal way of setting the Default Value for a Angular Material Select dropdown? The mat select is calling an API which populates the dropdown list. Then its preselecting the value to defaultAddressFormat
variable. Its being done in the subscribe function.
Curious if there is more optimal way of doing this,
this.addressService.getAddressFormatAll()
is an observable
After presetting value, user should be able to select different selection if needed.
If the default is set before API fully loads, sometimes it may not render, so being called in subscribe method.
this.addressService.getAddressFormatAll().subscribe(res => {
this.addressFormatList = res.body;
if (this.addressFormatList.length > 1) {
this.addressHeaderForm.patchValue({ addressFormat: this.defaultAddressFormat });
}
});
<mat-form-field>
<mat-label>Address Format</mat-label>
<mat-select
formControlName = "addressFormat"
[compareWith]="compareAddressFormatDataObjects"
placeholder ="Select"
(selectionChange)="addressFormatChangeEvent($event)" required >
<mat-option (click)="addressHeaderForm.controls.addressFormat.reset()">Select</mat-option>
<mat-option
*ngFor="let addressFormatItem of addressFormatList"
[value]="addressFormatItem"
>
{{addressFormatItem.addressFormatDescription}}
</mat-option>
</mat-select>
</mat-form-field>
Other resources: