'Why default value in mat-select doesn't display?
I have component1.ts:
selectOptions: [
{
value: 'HH:mm',
label: '24 - hour',
},
{
value: 'hh:mm a',
label: '12 - hour',
},
];
selected: string = 'SomeValue';
someForm: FormGroup;
ngOnInit(): void {
this.someForm= new FormGroup({
value: new FormControl(null)
})
}
component1.html
<form [formGroup]="someForm" class="form__wrapper">
<mat-form-field class="views__wrapper">
<mat-select formControlName="value" [(value)]="selected" class="cities__views">
<mat-option *ngFor="let option of viewsOptions" [value]="option">{{
option.label
}}</mat-option>
</mat-select>
</mat-form-field>
</form>
I can switch values, but when i open page, default value doesn't display

Solution 1:[1]
You can remove [(value)]="selected" from html and pass value in FormGroup
so:
this.someForm= new FormGroup({
value: new FormControl('HH:mm')
})
Solution 2:[2]
It doesn't display because in your array "selectOptions" the selected value "SomeValue" doesn't exist.
This should work:
TS:
selectOptions: [
{
value: 'SomeValue',
label: 'SomeValue',
},
{
value: 'HH:mm',
label: '24 - hour',
},
{
value: 'hh:mm a',
label: '12 - hour',
},
];
selected: string = 'SomeValue';
HTML:
<form [formGroup]="someForm" class="form__wrapper">
<mat-form-field class="views__wrapper">
<mat-select formControlName="value" [(value)]="selected" class="cities__views">
<mat-option *ngFor="let option of selectOptions" [value]="option.value">{{
option.label
}}</mat-option>
</mat-select>
</mat-form-field>
</form>
Or if you wants a timevalue directly
TS:
selectOptions: [
{
value: 'HH:mm',
label: '24 - hour',
},
{
value: 'hh:mm a',
label: '12 - hour',
},
];
selected: string = 'HH:mm';
HTML:
<form [formGroup]="someForm" class="form__wrapper">
<mat-form-field class="views__wrapper">
<mat-select formControlName="value" [(value)]="selected" class="cities__views">
<mat-option *ngFor="let option of selectOptions" [value]="option.value">{{
option.label
}}</mat-option>
</mat-select>
</mat-form-field>
</form>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mahdi Rezazadeh |
| Solution 2 | AndyNope |

