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
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;
}
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With