Angular 5 Reactive Forms - Radio Button Group

前端 未结 2 1207
抹茶落季
抹茶落季 2020-12-05 06:40

I have 2 radio buttons, I\'m using reactive forms and I have added the form controls within my component. The issue I am facing is that the name attribute has to be the same

相关标签:
2条回答
  • 2020-12-05 06:48

    I tried your code, you didn't assign/bind a value to your formControlName.

    In HTML file:

    <form [formGroup]="form">
       <label>
         <input type="radio" value="Male" formControlName="gender">
           <span>male</span>
       </label>
       <label>
         <input type="radio" value="Female" formControlName="gender">
           <span>female</span>
       </label>
    </form>
    

    In the TS file:

      form: FormGroup;
      constructor(fb: FormBuilder) {
        this.name = 'Angular2'
        this.form = fb.group({
          gender: ['', Validators.required]
        });
      }
    

    Make sure you use Reactive form properly: [formGroup]="form" and you don't need the name attribute.

    In my sample. words male and female in span tags are the values display along the radio button and Male and Female values are bind to formControlName

    See the screenshot:

    To make it shorter:

    <form [formGroup]="form">
      <input type="radio" value='Male' formControlName="gender" >Male
      <input type="radio" value='Female' formControlName="gender">Female
    </form>
    

    Hope it helps:)

    0 讨论(0)
  • 2020-12-05 06:54

    IF you want to derive usg Boolean true False need to add "[]" around value

    <form [formGroup]="form">
      <input type="radio" [value]=true formControlName="gender" >Male
      <input type="radio" [value]=false formControlName="gender">Female
    </form>
    
    0 讨论(0)
提交回复
热议问题