koque
koque

Reputation: 2256

How do I dynamically assign true or false to a radio button "checked" attribute?

I am iterating over an array of data as shown here:

<div class="row mt-2">
    <div class="col d-flex justify-content-center">
        <input *ngFor="let radio of template.selection" 
            type="radio" class="mr-1" 
            name="{{radio.name}}" 
            checked="{{radio.checked}}">        
    </div>  
</div>

I want to dynamically assign true or false to the "checked" attribute of the radio button based on the "checked" field of selection array shown below but this not working.

Data:

selection: [
   {name: 'none', checked:true},
   {name: 'full', checked:false},
   {name: 'right', checked:false},
   {name: 'left', checked:false},                    
]

Upvotes: 0

Views: 96

Answers (2)

robert
robert

Reputation: 6152

If you are using radio buttons consider the following setup.

  selection = [
    { name: 'none' },
    { name: 'full' },
    { name: 'right' },
    { name: 'left' },
  ]

  selectedValue = 'full';

html:

<ng-container *ngFor="let r of selection">
  <input  type="radio" name="some" [value]="r.name" [(ngModel)]="selectedValue">{{r.name}}
</ng-container>

<pre>
  {{ selectedValue }}
</pre>

Stackblitz

Upvotes: 0

asimhashmi
asimhashmi

Reputation: 4378

First of all, your data should be:

selection =  [
   {name: 'none', checked:true},
   {name: 'full', checked:false},
   {name: 'right', checked:false},
   {name: 'left', checked:false},                    
]

Use [checked] instead of checked

<div class="row mt-2">
    <div class="col d-flex justify-content-center">
        <input *ngFor="let radio of selection" 
            type="radio" class="mr-1" 
            name="{{radio.name}}" 
            [checked]="radio.checked">        
    </div>  
</div> 

Working Stackblitz demo

Upvotes: 1

Related Questions