您可以使用 Angular's Reactive Forms ,像这样:
应用模块:
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
// other imports ...
ReactiveFormsModule
],
})
export class AppModule { }
您的组件:
import {FormControl, FormGroupDirective, FormGroup, NgForm, Validators} from '@angular/forms';
...
export class SoknadsskjemaComponent implements OnInit {
...
myForm = new FormGroup({
gender: new FormControl('', [
Validators.required
]),
name: new FormControl('', [
Validators.required,
Validators.minLength(2)
]),
birthdate: new FormControl('', [
Validators.required,
]),
});
onSubmit() {
// Do somthing
// You can get the values in the forms like this: this.myForm.value
}
}
你的组件 html
<form autocomplete="on" [formGroup]="myForm" (ngSubmit)="onSubmit()">
<mat-radio-group #rGroup class="radio-group" formControlName="gender">
<mat-radio-button class="radio-button" value="female" radioGroup="rGroup">Female</mat-radio-button>
<mat-radio-button class="radio-button" value="male" radioGroup="rGroup">Male</mat-radio-group>
</mat-radio-group>
<mat-form-field appearance="outline" class="full-width">
<mat-label>Birthdate</mat-label>
<input matInput [matDatepicker]="picker" formControlName="birthdate" autocomplete="bday">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker touchUi startView="multi-year" [startAt]="startDate" #picker></mat-datepicker>
</mat-form-field>
<mat-form-field appearance="outline" class="full-width">
<mat-label>Name</mat-label>
<input matInput type="text" formControlName="name" name="given-name" autocomplete="given-name">
</mat-form-field>
<button mat-stroked-button type="submit" [disabled]="!myForm.valid" style="width:100%">Submitt</button>
</form>