Hay
I have input select with label(value) and key(id)
whan I click on submit I want to get key(id)
<form (submit)="onSubmit(testForm)" [formGroup]="form">
<mat-form-field>
<input matInput type="text" name="user" [formControlName]="username" id="userid" required>
</mat-form-field>
<button mat-raised-button color="primary" type="submit">submit</button>
</form>
//I expect to receive [id] value form.controls.username … id
1
You have to use property binding for the [value]
and ensure you set the key for it.
You are not supposed to use required
since it works better with template driven forms, instead use Validators.required
.
Also prefer (ngSubmit)
instead of (submit)
.
Docs for 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);
}
}
Stackblitz Demo
1