dynamic list of radiobuttons in angular
Asked Answered
E

2

7

I have a list of radiobuttons that are not a part of a form. I would like to set to true just one of them, according to a value.

Then, when another one is clicked, all the others are set to false, except the clicked one.

The radiobuttons list is dynamic, generated by a ngFor,

I have something like

<div *ngFor='let item of array;let i = index'>                    
   <input type="radio" [checked]=false (click)='radioChecked(item.id,i)' > <input type="text" value='{{item.name}}' >  <button type="button" >save</button>                    
 </div>  

ngOnInit() {  
  this.myService.getNumber(id).subscribe((data) =>{  
  //when the page loads, set one of radiobuttons to true
  //somehow get the id and set to true, no standard is, since dynamic list
  radioId.value = true;
  })
}

radioChecked(id, i){
  //turn all the others to false, except this one
}

Since this is not in a form and there is no standard rows, so I can have an id, how can I do this? I use angular 6

Thanks

Elk answered 27/10, 2018 at 18:26 Comment(0)
E
8

selected property should be part of the item object in an array.

Template:

    <div *ngFor='let item of array;let i = index'>                    
       <input type="radio" [checked]="item.selected" (change)='radioChecked(item.id,i)' > 
        <input type="text" value='{{item.name}}'/>  
        <button type="button">save</button>                    
     </div> 

Component:

 radioChecked(id, i){
  array.forEach(item=>{
    if(item.id !== id){ 
       item.selected = false;
    }else{
       item.selected = true;
    } 
  })
}
Eldredge answered 27/10, 2018 at 18:45 Comment(1)
Thanks Suresh. I also dont see any other solution except putting item.selected in the objectElk
H
-1

Actually, the correct answer is to use (click) not (change)

Horseflesh answered 10/2, 2020 at 16:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.