How to set radio button value using Reactive form?

房东的猫 提交于 2019-12-21 04:23:14

问题


Here is my component class where I try to set a form radio button value to 1:

import { FormGroup, FormControl } from '@angular/forms';

export class myComponent implements OnInit{
    pageForm: FormGroup;

    ngOnInit() {
        this.pageForm = new FormGroup({
            'gndr': new FormControl(1)
        });
    }
}

but when the page loaded the Radio button is not set to Male and both options are blank:

<div class="form-group">
    <label for="gender">Gender</label>
    <div class="radio">
        <label>
            <input type="radio" name="gndr" formControlName="gndr" value=1>Male
        </label>
    </div>
    <div class="radio">
        <label>
            <input type="radio" name="gndr" formControlName="gndr" value=0>Female
        </label>
    </div>
</div>

so how can I load radio button value from my component class?


回答1:


If you want either one of them to be checked by default manually, you can add the "checked" tag e.g.

<div class="radio">
    <label>
        <input type="radio" name="gndr" formControlName="gndr" value=1 checked>Male
    </label>
</div>
<div class="radio">
    <label>
        <input type="radio" name="gndr" formControlName="gndr" value=0>Female
    </label>
</div>

Edit

If you want to use the default value as of type string, set in the FormControl:

component.ts

this.pageForm = new FormGroup({
      'gndr': new FormControl('1')
    });

component.html

...
<input type="radio" formControlName="gndr" value=1>
...

If you want to use the default value as of type number, set in the FormControl:

component.ts

this.pageForm = new FormGroup({
      'gndr': new FormControl(1)
    });

component.html

...
<input type="radio" formControlName="gndr" [value]=1>
...


来源:https://stackoverflow.com/questions/46720407/how-to-set-radio-button-value-using-reactive-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!