首页 文章

Angular2 Reactive Forms formControl用于单选按钮

提问于
浏览
31

我正在使用Reactive Forms在Angular2中构建一个表单 . 我正在使用FormBuilder来创建一组字段 . 对于文本框,这非常有效 . 但我找不到单选按钮的formControl .

这是如何运作的?我应该像文字输入一样做 <input formControlName="gender" type="radio"> 吗?

4 回答

  • 26

    我应该<输入formControlName =“gender”type =“radio”>就像我使用文本输入一样吗?

    是 .

    这是如何工作的?

    表单控件指令使用 ControlValueAccessor 指令与本机元素进行通信 . 每种可能的输入都有不同类型的 ControlValueAccessors . 正确的一个由值访问器指令的 selector 选择 . 选择器基于 type <input> . 当你有 type="radio" 时,将使用无线电的值访问器 .

  • 2

    在组件中,将单选按钮定义为表单的一部分:

    export class MyComponent {
      form: FormGroup;
      constructor(fb: FormBuilder){
        this.form = fb.group({
          gender: ""
        });
      }
    }
    

    在组件HTML中,构建表单:

    <div class="form-group">
      <label>Please select your gender</label>
      <div class="row">
        <label class="md-check">
          <input type="radio" value="female" name="gender" formControlName="gender">
          Female
        </label>
    
        <label class="md-check">
          <input type="radio" value="male" name="gender" formControlName="gender">     
          Male
        </label>
      </div>
    </div>
    

    我假设您知道如何使用提交按钮构建整个表单,此处未显示 .

    提交表单后,您可以在此处获取单选按钮的值:

    let genderValue = this.form.value.gender;
    

    根据检查的单选按钮,这将是“女性”或“男性” .

    希望这对你有所帮助 . 祝好运!

  • 30

    一个小的添加关于我注意到的反应形式 . 如果值是整数,则需要将其更改为字符串,否则不会选择单选按钮 .

    this.jobForm = this._fb.group({
                        id: [res["job"]["id"]],
                        job_status: [res["job"]["job_status"]**["id"].toString()**,Validators.required],
                        title: [res["job"]["title"],Validators.required]
                    });
    
  • 4

    Angular Material controls(大部分)已经足够成熟,现在可以使用 .

    他们的样本大多使用ngModel,但是你可以使用formControlName来完成它 .

    <mat-radio-group formControlName="colorFilter" fxLayout="column" fxLayoutGap=".25rem">
        <mat-radio-button [value]="'Blue'">Blue things</mat-radio-button>
        <mat-radio-button [value]="'Red'">Red things</mat-radio-button>
        <mat-radio-button [value]="'Orange'">Orange things</mat-radio-button>
    </mat-radio-group>
    

    我正在使用angular/flex-layout将我的按钮放在垂直列中 .

    (也可以为常量完成 value='Blue'[value]="blueColorName" 来引用模型属性 .

    我相信 0 可能存在问题,因为它不是'truthy'值,因此请注意您是否绑定枚举(可能不再是问题) .

相关问题