It is recommended to utilize property binding for the [value]
attribute and ensure that a key is set.
Avoid using required
as it works more effectively with template-driven forms, instead use Validators.required
.
Additionally, opt for (ngSubmit)
over (submit)
.
Explore the documentation on reactive forms
<form (ngSubmit)="onSubmit()" [formGroup]="form">
<input
matInput
type="text"
name="user"
formControlName="username"
id="userid"
/>
<mat-form-field>
<mat-label>Favorite food</mat-label>
<mat-select formControlName="food">
@for (food of foods; track food) {
<mat-option [value]="food.value">{{food.viewValue}}</mat-option>
}
</mat-select>
</mat-form-field>
<button mat-raised-button color="primary" type="submit">submit</button>
</form>
TS:
import { Component } from '@angular/core';
import {
ReactiveFormsModule,
FormGroup,
FormControl,
Validators,
} from '@angular/forms';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { MatFormFieldModule } from '@angular/material/form-field';
interface Food {
value: string;
viewValue: string;
}
/**
* @title Basic select
*/
@Component({
selector: 'select-overview-example',
templateUrl: 'select-overview-example.html',
standalone: true,
imports: [
MatFormFieldModule,
MatSelectModule,
MatInputModule,
ReactiveFormsModule,
],
})
export class SelectOverviewExample {
form = new FormGroup({
food: new FormControl('', Validators.required),
username: new FormControl('', Validators.required),
});
foods: Food[] = [
{ value: 'steak-0', viewValue: 'Steak' },
{ value: 'pizza-1', viewValue: 'Pizza' },
{ value: 'tacos-2', viewValue: 'Tacos' },
];
onSubmit() {
console.log(this.form.value);
}
}