我们如何在角度2中设置单选按钮的默认值 [英] How can we set the default value of radio button in angular 2
本文介绍了我们如何在角度2中设置单选按钮的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个模型驱动的表单,想显示基于无线电输入的字段.代码:-
I have a Model driven form and want to show the fields based on radio input. Code :-
<div class="form-group">
<md-radio-group class="form-control" id="radio1" formControlName="selection">
<md-radio-button [value]="A" >A</md-radio-button>
<md-radio-button [value]="B">B</md-radio-button>
</md-radio-group>
</div>
<div class="form-group" *ngIf="selection.value=='A'">
<md-input-container>
<textarea md-input placeholder="A" class="form-control"
formControlName="A"
style="border:none;"></textarea>
</md-input-container>
</div>
<div class="form-group" *ngIf="selection.value=='B'">
<md-input-container>
<input md-input placeholder="B" class="form-control"
formControlName="B"
style="border:none;">
</md-input-container>
</div>
由于无法读取未定义的属性'值'"而出现错误由于未选择任何广播.
Getting error as "Cannot read property 'value' of undefined" As no radio is selected.
我如何指定选择第一个作为默认值.
How can I specify to select the first one as default.
推荐答案
您需要传递 string
作为收音机的值.现在,Angular试图找到名称为 A
的变量.
You need to pass a string
as a value for the radio. Right now Angular tries to find a variable with the name A
.
<md-radio-group class="form-control" [(ngModel)]="selection.value"
id="radio1" formControlName="selection">
<md-radio-button [value]="'A'">A</md-radio-button>
<md-radio-button [value]="'B'">B</md-radio-button>
</md-radio-group>
您在对相应组件中的 selection.value
分配值时初始化无线电:
You initialize the radio as you assign a value to selection.value
in the according component:
class MyRadioComponent {
selection = {"value":"A"};
}
这篇关于我们如何在角度2中设置单选按钮的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文