Reputation: 152
I am trying to get value of radio button . This HTML
<div class="col-md-4" *ngFor="let option of mainOption?.options[0]?.suboptions, let i = index " style="padding: 0;width: 100%;">
<div class="row" style="margin: 0;">
<div class="changed p-0" style="width: 15px;place-self: center;">
<input type="radio" class="float-right form-check-input position-static"
name="{{option.extra_option_id}}" [value]='option' [(ngModel)]="option[i]"
(ngModelChange)='changeEventInRadioButton($event)' style="margin: 0;">
</div>
<div class="col-8 p-2">
<div class="float-left">
<span class="inputdisplay">{{ option.name }}</span>
<br>
<span class="inputdisplay1" style="font-size: 14px;">+ {{ option.price | currency }}</span>
</div>
</div>
</div>
</div>
Here are two variable with same name option
one is object
other is an array
which is global
No I am trying to get value of this radio button it works fine when name is same for both variables
which is this object
{
"id": 267,
"suboptions": [
{
"id": 765,
"name": "Fanta",
"price": 2,
"position": "whole",
"quantity": 1
}
]
}
This object is created inside changeEventInRadioButton
function
changeEventInRadioButton(val) {
console.log('gh',val);
console.log('Array',this.option)
// this.option = [];
let suboptions = [
{
"id": val.id,
"name": val.name,
"price": val.price,
"position": "whole",
"quantity": 1
}
];
let data = {
"id": val.extra_option_id,
"suboptions": suboptions
};
let obj = this.option.some(obj => obj.id == data.id);
console.log('id',obj,'data',data.id)
if(obj){
console.log('cc',obj)
let objIndex = this.option.findIndex((obj => obj.id == data.id));
this.option[objIndex].suboptions = suboptions;
}else{
this.option.push(data);
}
console.log("Option Value ", this.option);
}
but when i change the name of object
variable then it gives me this this value for this.option
[
{
"id": 749,
"extra_option_id": 262,
"name": "Small",
"price": 1,
"image": null,
"sku": null,
"rank": 1,
"description": null,
"max": 1,
"half_price": null,
"enabled": true,
"created_at": "2021-02-10 16:54:08",
"updated_at": "2021-02-19 05:43:45",
"deleted_at": null
},
{
"id": 262,
"suboptions": [
{
"id": 749,
"name": "Small",
"price": 1,
"position": "whole",
"quantity": 1
}
]
}
]
you see one additional object is added at index 0
Why is this happpening?
Upvotes: 0
Views: 439
Reputation: 53
To use object array with radio buttons you can use the code below =>
TS
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
favoriteSeason1: string;
tests: Test[] = [{name:'sjn',id:1},{name:'sjnf',id:2},{name:'ilysna',id:3}];
}
export class Test{
name:string ;
id:number;
}
HTML:
<div *ngFor="let tt of tests; let i = index">
<input id="tt.name{{i}}" name="seasons" type="radio"
[value]="tt.name" [(ngModel)]="favoriteSeason1" />
<label for="">{{tt.name}}</label>
</div>
You can check the StackBlitz link
Upvotes: 2