简体   繁体   中英

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.

Setting optionSelected to the value of the option you want to select should work, something like:

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.

A quick fix would be to force optionSelected to be a string as well:

this.optionSelected = option[0].optionId + '';

The correct way to fix this is by using data binding to set the value attribute.

In Angular (Angular 2 and 4):

[value]="optionSelected"

In AngularJS (Angular 1):

ng-value="optionSelected"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM