这是我的组件类,我尝试将表单单选按钮值设置为1:
import { FormGroup, FormControl } from '@angular/forms';
export class myComponent implements OnInit{
pageForm: FormGroup;
ngOnInit() {
this.pageForm = new FormGroup({
'gndr': new FormControl(1)
});
}
}
但是当加载页面时,“单选按钮”未设置为“男性”且两个选项均为空白:
<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>
那么如何从我的组件类中加载单选按钮值?
答案 0 :(得分:10)
如果您希望手动选中其中任何一个,则可以添加&#34;选中&#34;标记例如
<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中设置:
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': new FormControl(1)
});
component.html
...
<input type="radio" formControlName="gndr" [value]=1>
...