koque
koque

Reputation: 2256

Angular: "checked" attribute of radio input not working as expected

In the code shown below,

I am iterating over deliveryMethods which are displayed in the view as radio buttons. I intend to have the first radio button pre-selected.

I applied the following attribute:

[checked]="ndx==0"

where ndx is the index of each iteration. But none of the radio button is checked.

How do I dynamically pre-select the first radio button?

<div *ngFor="let dm of deliveryMethods; let ndx=index">
   <label class="form-check-label">
      <input class="form-check-input f-s-1pt2" type="radio" 
             name="dm.name" 
             value="{{dm.name}}" 
             [(ngModel)]="item.item.deliveryMethod"
             (change)="filterProducts(item)"
             [checked]="ndx==0"
             class="radio-dimension"> 
             {{dm.label}}
   </label>
</div>

Upvotes: 8

Views: 14889

Answers (2)

shehan96
shehan96

Reputation: 388

If you want to keep [(ngModel)] without removing it just use following syntax in angular

<input class="form-check-input" type="radio" name="flexRadioDefault" id="flexRadioDefault1"
                                #is_public="ngModel" name="is_public" [(ngModel)]="updateGroupData.is_public" [value]="1">

Keep in mind to use [value] for data binding.

OR

Use this with true and false

<input class="form-check-input" type="radio" id="flexRadioDefault2" #is_public="ngModel" name="is_public [(ngModel)]="groupFormData.is_public" [value]="false">

Keep in mind to use [value]="true" or [value]="false" for data binding.

Upvotes: 1

Niladri
Niladri

Reputation: 5962

I have removed the [(ngModel)] and use property binding with [value] to bind the value to the radio button control . The below code works for me

<div *ngFor="let dm of deliveryMethods; let ndx = index">
              <label class="form-check-label">
                    <input class="form-check-input f-s-1pt2" type="radio" 
                      name="dm.name" 
                      [value]="dm.name"
                      (change)="filterProducts(item)"
                      [checked]="ndx === 0"
                      class="radio-dimension"> 
                      {{dm.label}}
             </label> 
       </div>

Here is a working plunker https://plnkr.co/edit/6Ay2zr7Ow3csB5Pxdgdz?p=preview

Upvotes: 6

Related Questions