indu ECE
indu ECE

Reputation: 85

Angular:how to implement custom radio button dynamically in angular

I designed custom radio button, this is working proper in static but when i make dynamic, that time it act like checkbox.

<div *ngFor="let currentwork of currentworks">
    <label class="customcheck">{{currentwork}}
        <input type="radio" name="{{currentwork}}">
        <span class="checkmark"></span>
    </label>&nbsp;
</div>            

If I put name={{currentwork}}, it will act like checkbox. I want radio button with one selection. I don't know why it's coming like this, please help me.

Upvotes: 1

Views: 6257

Answers (4)

Giacomo Rocco
Giacomo Rocco

Reputation: 33

For radio buttons to work you need to give the same name and for each option give a value.

A working example should be:

<div *ngFor="let currentwork of currentworks">
    <label class="customcheck">{{currentwork}}
    <input type="radio" name="options" value="{{currentwork}}">
    <span class="checkmark"></span>
    </label>&nbsp;
</div>  

As you can see I give a name (options) that is the same for all input values, and then using currentwork as value.

Here a working example (check app.ts)

Edit: you can even generate multiple radio selection. But you should share an example of your dynamic data.

http://next.plnkr.co/edit/zuhY7kgzPj6141oY?preview

Upvotes: 1

zmag
zmag

Reputation: 8261

Names of radio buttons must be the same.

This may works:

<div *ngFor="let currentwork of currentworks">
  <label class="customcheck">{{currentwork}}
    <input type="radio" name="currentworks" [value]="currentwork">
    <span class="checkmark"></span>
  </label>&nbsp;
</div>   

Upvotes: 2

Raj
Raj

Reputation: 374

With reactive form approach, you can use like -

<div *ngFor="let currentwork of currentworks">
  <label class="customcheck">
     <input type="radio" [value]="currentwork.id" 
       formControlName="radiobuttoncontrolname">
     <span class="checkmark"></span>
     <span class="customcheck">{{currentwork.Name}}</span>
  </label>
</div>

I am assuming that you are having your currentWorks as -

currentWorks = [
 { id: 'something', Name: 'something' },
 { id: 'something2', Name: 'something2' }
];

Upvotes: 1

Igor
Igor

Reputation: 62298

You need to set the value, not the name, for each option. The name should be the same for each option. You can also use the binding bracket notation [value] over value="{{}}.

<div *ngFor="let currentwork of currentworks">
  <label class="customcheck">{{currentwork}}
    <input name="myRadioButton" type="radio" [value]="currentwork">
    <span class="checkmark"></span>
  </label>&nbsp;
</div>  

Stackblitz

Upvotes: 2

Related Questions