0

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.

1 Answer 1

1

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"
Sign up to request clarification or add additional context in comments.

4 Comments

I have done something similar. The optionSelected contains valid value in my code.
@sudheer-singh When you use value instead of ng-value, the value will always be interpreted as a string. Probably this.optionSelected = option[0].optionId + ''; will work. If you don't want to do this, then use ng-value in your HTML instead.
changing value to [value] worked. Thanks for pointing that out.
@sudheer-singh Updated the answer to reflect what we discussed in the comments and to point out the solution for both AngularJS and Angular.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.