角材料:从形式中获取价值

时间:2018-10-21 15:37:18

标签: javascript angular forms angular-material

我正在Angular上编写注册页面。两个单选按钮用于选择您是男人还是女人。另外,您还可以输入其他数据,例如姓名和地址。单击页面末尾的按钮应发送注册。

如何最好地做到我要在Typescript文件中获取值?

以下是我要使用的组件:

InputSelectRadio ButtonDate Picker

https://material.angular.io/components/input/overview

https://material.angular.io/components/select/overview

https://material.angular.io/components/radio/overview

https://material.angular.io/components/datepicker/overview

1 个答案:

答案 0 :(得分:0)

您可以使用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>