如何使用反应形式设置单选按钮值? [英] How to set radio button value using Reactive form?
问题描述
这是我的组件类,在这里我尝试将表单单选按钮的值设置为1:
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?
推荐答案
如果您希望默认情况下手动检查其中任何一个,则可以添加"checked"标记,例如
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>
修改
如果要使用类型字符串的默认值,请在FormControl中设置:
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>
...
如果要使用默认值作为类型编号,请在FormControl中进行设置:
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>
...
这篇关于如何使用反应形式设置单选按钮值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!