简体   繁体   中英

How to put radio button logic in *ngFor?

i have options populated in the form with radio buttons now when i select one of the option i dont see isChecked true , am i missing anything below using angular ?

app.component.html

<div class="form-group">
 <label>answerOption</label>
    <div *ngFor="let option of singleQuestion.answerOption">
        <label>
           <input type="radio" name="option.isChecked" 
              [value]="true" (change) ="handleChange(option.isChecked)">
                 {{option.answerText}}
        </label>
   </div>

First you need the group the radio button and this is done by providing the same name for the radio buttons.

example:-

<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other

So when the user can check only one option at a time.

For your example, I have given name has question.

We need to understand which option is selected by user, so you need bind a unique value, in my above given gender example, I have added different value for each radio control value.

 [value]="option.answerOptionId"

Here, [value] is one way binding, from code to view therefore the ischecked it not set to true. Better way is given below.

       <div class="form-group">
          <label>answerOption</label>
            <div *ngFor="let option of singleQuestion">
                <label>
                <input type="radio" name="question" 
         [value]="option.answerOptionId" (change) ="handleChange(option)">
                {{option.answerText}}
                </label>
            </div>
        </div>

The best thing i can choose from your option is option.answerOptionId, refer my above html snippet. Sending the current radio button, option.isChecked is not correct, since we will always get false. Reason you have provided the value false for both the answer option in ts file. For the event I have sent whole radio control. Log method in ts file will show you the current option selected by user.

To sum up.

  • Same name for radio button.
  • Provide different value for each radio button.
  • Send the control or the control value in the event, whichever is favorable.

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