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" >
<mat-form-field >
<mat-select formControlName="value" [(value)]="selected" >
<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
CodePudding user response:
You can remove [(value)]="selected" from html and pass value in FormGroup
so:
this.someForm= new FormGroup({
value: new FormControl('HH:mm')
})
CodePudding user response:
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" >
<mat-form-field >
<mat-select formControlName="value" [(value)]="selected" >
<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" >
<mat-form-field >
<mat-select formControlName="value" [(value)]="selected" >
<mat-option *ngFor="let option of selectOptions" [value]="option.value">{{
option.label
}}</mat-option>
</mat-select>
</mat-form-field>
</form>