本文介绍了如何使用反应式表单设置单选按钮值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我尝试将表单单选按钮值设置为 1 的组件类:
import { FormGroup, FormControl } from '@angular/forms';导出类 myComponent 实现 OnInit{pageForm:表单组;ngOnInit() {this.pageForm = new FormGroup({'gndr': 新的 FormControl(1)});}}
但是当页面加载时,单选按钮没有设置为男性并且两个选项都是空白的:
<label for="gender">性别</label><div class="radio"><标签><input type="radio" name="gndr" formControlName="gndr" value=1>男标签>
<div class="radio"><标签><input type="radio" name="gndr" formControlName="gndr" value=0>女标签>
那么如何从组件类加载单选按钮值?
解决方案
如果您希望在默认情况下手动检查其中之一,您可以添加已检查"标签,例如
<标签><input type="radio" name="gndr" formControlName="gndr" value=1 选中>男标签>
<div class="radio"><标签><input type="radio" name="gndr" formControlName="gndr" value=0>女标签>
编辑
如果要使用类型字符串的默认值,请在FormControl中设置:
component.ts
this.pageForm = new FormGroup({'gndr': new FormControl('1')});
component.html
...<input type="radio" formControlName="gndr" value=1>...
如果要使用类型编号的默认值,请在FormControl中设置:
component.ts
this.pageForm = new FormGroup({'gndr': 新的 FormControl(1)});
component.html
...<input type="radio" formControlName="gndr" [value]=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?
解决方案
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>
...
这篇关于如何使用反应式表单设置单选按钮值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!