[英]How to pre-select radio button when using two-way binding in Angular?
I am trying to fetch some radio inputs and one of them has to be preselected. 我正在尝试获取一些无线电输入,并且其中之一必须预先选择。
Following is the code: 以下是代码:
<div class='form-group que-box' *ngFor="let option of options">
<input type='radio' id="{{option.optionId}}" name="radio" [(ngModel)]="optionSelected" value='{{option.optionId}}'>
<label for='{{option.optionId}}'><span class="que">{{option.text}}</span></label>
</div>
But the button doesn't get preselected.I tried conditionally putting checked
attribute there but that also doesn't help.The Html is rendered with the checked
attribute but still the option doesn't get preselected.I have also checked that optionSelected
always contain desirable value. 但是按钮没有被预先选择。我尝试有条件地将
checked
属性放在那里,但这也无济于事.HTML带有checked
属性呈现,但选项仍然未被预先选择。我还检查了optionSelected
始终包含理想的价值。
Setting optionSelected
to the value of the option you want to select should work, something like: 将
optionSelected
设置为要选择的选项的值应该可以,例如:
this.optionSelected = option[0].optionId;
If optionId
is a number or anything else than a string, then setting the value using interpolation ( value='{{ option.optionId }}'
) will not work, as it will be evaluated as string, so it will not match optionSelected
when checked using strict equality ( ===
) , which Angular is using under the hood. 如果
optionId
是数字或字符串以外的其他内容,则无法使用插值 ( value='{{ option.optionId }}'
)设置值,因为它将被评估为字符串,因此将与optionSelected
不匹配使用严格等于( ===
)检查,Angular在引擎盖下使用。
A quick fix would be to force optionSelected
to be a string as well: 一个快速的解决方法是将
optionSelected
也强制为字符串:
this.optionSelected = option[0].optionId + '';
The correct way to fix this is by using data binding to set the value
attribute. 解决此问题的正确方法是使用数据绑定设置
value
属性。
In Angular (Angular 2 and 4): 在Angular中(Angular 2和4):
[value]="optionSelected"
In AngularJS (Angular 1): 在AngularJS(Angular 1)中:
ng-value="optionSelected"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.