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>
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.
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).
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 .
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With