Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic list of radiobuttons in angular

Tags:

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

like image 468
codebot Avatar asked Oct 27 '18 18:10

codebot


1 Answers

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;
    } 
  })
}
like image 55
Suresh Kumar Ariya Avatar answered Nov 15 '22 04:11

Suresh Kumar Ariya