Creating multiple radio buttons with *ngFor [Angul

2020-02-29 04:10发布

问题:

I need dynamic number of radio buttons based on the length of Array Of Objects (eg: enum_details):

Following is the code I tried:

<div *ngFor="let enum of enum_details">
  <label for="enum_answer_{{enum.value}}">
    <input id="enum_answer_{{enum.value}}" type="radio" name="enums" [(ngModel)]="enum.value">
    {{enum.display_text}}
  </label>
</div>

But, when I click any radio, always the last one gets selected and the value is never assigned to ngModel.

If I remove ngModel, the radios work fine, but, value is not set. What can be the fix here?

回答1:

use your code like this

<div *ngFor="let enum of enum_details">
      <label for="enum_answer_{{enum.name}}">
        <input id="enum_answer_{{enum.name}}" [value]='enum.name' type="radio" name="enums" [(ngModel)]="radioSelected">
        {{enum.name}}
      </label>
    </div>
    <button (click)='radioFun()'>Checked value of radio button</button>

working example

Working example here



回答2:

Try something like this.

   <div class="radio" *ngFor="let key of enum_details">
          <label>
                 <input type="radio" name="keys_on_hand" [value]="key.value" [(ngModel)]="key.value">
                   {{key.display}}
          </label>
    </div>


回答3:

Building on @Pardeep's response, you should also make the buttons keyboard accessible for users that want/need it. Add tabindex and a keyup listener on your labels:

<div *ngFor="let enum of enum_details">
  <label for="enum_answer_{{enum.name}}" tabindex="0" (keyup.space)="radioSelected=enum.name'>
    <input id="enum_answer_{{enum.name}}" [value]='enum.name' type="radio" name="enums" [(ngModel)]="radioSelected">
    {{enum.name}}
  </label>
</div>


标签: angular