Reputation: 177
I have a list of values that are to be displayed as Radio buttons. Each radio button has a value with certain count that will be decreased if the radio button is selected. If radioButton1 is selected then the count becomes 1, if some other radio button say radioButton2 in this list is selected then the count of the radioButton1 is restored to its original value and the count for the radionButton2 is decreased by one. I have been trying to find a solution to this but haven't been able to. Any help will be greatly appreciated thanks!
app.component.ts
this.itemList = [
{ name: 'item1', count: 1},
{ name: 'item2', count: 2},
{ name: 'item3', count: 3},
{ name: 'item4', count: 2},
{ name: 'item5', count: 1},
]
onRadioSelect(userSelect){
this.itemList.forEach((selected,index)=>{
if(selected.name === userSelect.value){
selected.count -= 1;
if(selected.count === 0){
this.countZeroDisable= index;
}
}
app.component.html
<div *ngFor="let items of itemList; let idx = index" [ngClass]="{'disable': idx===countZeroDisable}">
<input type="radio" name="List1" [value]="items.name" [disabled]="idx===countZeroDisable" (change)= onRadioSelect(List1) #List1>
{{items.name}}({{items.count}})
</div>
Upvotes: 2
Views: 880
Reputation: 15423
Make the following change:
.ts
onRadioSelect(userSelect) {
this.itemList.forEach(e => {
if (e['selected']) {
e.count = e.count + 1;
e['selected'] = false;
}
if (e.name === userSelect.value) {
e.count -= 1;
e['selected'] = true;
}
})
}
.html
<div *ngFor="let items of itemList">
<input type="radio" name="List1" [value]="items.name" [disabled]="items.count === 0"
(change)=onRadioSelect(List1) #List1>
{{items.name}}({{items.count}})
</div>
To simplify things, a new field called selected is added to determine which is the index currently selected. If the index was previously selected then the count is reset else the count is incremented.
Upvotes: 1
Reputation: 1
In app.component.html
Change the method
onRadioSelect(List1)
to
onRadioSelect(items)
So you can take the selected item form onRadioSelect
.
Upvotes: 0
Reputation: 36
you can use FormControl and angular handle this for you try to use ReactiveFormModule and other parts of form in angular. it's easy to use and very helpful.
Upvotes: 0