Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angular

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>
like image 574
koque Avatar asked Jan 23 '18 17:01

koque


People also ask

Does checked work for radio buttons?

If a radio button is checked, its checked property is true . Then, we assign the value of the selected radio button to the selectedSize variable. Since only one radio button in a radio group can be checked at a time, the loop is terminated immediately by the break statement.

Why radio button is not getting selected?

You cannot unselect radio buttons. That's because they're used if you want the user to select either option1 or option2 or option3 but prohibit selecting multiple values or leaving it empty (e.g. in case of selecting a Gender).

How do I uncheck a radio button?

To set a radio button to checked/unchecked, select the element and set its checked property to true or false , e.g. myRadio. checked = true .

How do I group radio buttons in HTML?

Note: The radio group must have share the same name (the value of the name attribute) to be treated as a group. Once the radio group is created, selecting any radio button in that group automatically deselects any other selected radio button in the same group.


1 Answers

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

like image 148
Niladri Avatar answered Oct 08 '22 06:10

Niladri