Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly add "checked" to a radio button group in a loop?

Tags:

angular

Usually checked just add at the end of input

<input type="radio" name="item" value="value1" checked>
<input type="radio" name="item" value="value2">

But now I am using *ngFor. I want to select the first one.

I try to do this, but it does not work, because checked is not a class.

<div *ngFor="#item of collection; #i = index"">
    <input type="radio" name="item" value="{{item}}" [ngClass]="{'checked':i === 0}">
    <label>{{item}}</label>
</div>

So how can I do it? Thanks!

like image 783
Hongbo Miao Avatar asked Feb 16 '16 22:02

Hongbo Miao


People also ask

Does checked work for radio buttons?

The checked property sets or returns the checked state of a radio button. This property reflects the HTML checked attribute.

How do I keep my radio button checked?

You can check a radio button by default by adding the checked HTML attribute to the <input> element. You can disable a radio button by adding the disabled HTML attribute to both the <label> and the <input> .

What is group value in radio button?

Value. The value attribute is a string containing the radio button's value. The value is never shown to the user by their user agent. Instead, it's used to identify which radio button in a group is selected.


1 Answers

<input type="radio" name="item" value="{{item}}" [attr.checked]="i === 0 ? '' : null">
like image 113
Sasxa Avatar answered Oct 01 '22 10:10

Sasxa