Reputation: 1629
I need to get value from radio button in angular. Suppose to have this html code:
<label class="radio-inline">
<input class="form-check-input" type="radio" [(ngModel)]="dog" name="gob" value="i" [checked]="true" (change)="onItemChange(item)"/>Dog
</label>
<label class="radio-inline">
<input class="form-check-input" type="radio" [(ngModel)]="cat" name="cat" value="p" (change)="onItemChange(item)"/>Cat
</label>
In my ts page I need to get the value of radio button like
dog.value
My purpose is:
Anyone can help me?
Upvotes: 27
Views: 159993
Reputation: 1261
In your code, in order to group the radio buttons, they should have the same input for name
attribute.
To solve your problem, you can use *ngFor
to loop through the radio inputs,
HTML:
<div *ngFor="let opt of options; let i=index">
<label class="radio-inline">
<input type="radio" class="form-check-input" [value]="opt.value" [name]="opt.name" [checked]="i == 0"
(change)="onRadioChange(opt)"/>
</label>
</div>
TS:
interface Option {
name: string;
value: string;
}
options: Option[] = [
{
name: "pet",
value: "dog"
},
{
name: "pet",
value: "cat"
}
]
onRadioChange(opt: Option) {
console.log(`Value is: ${opt.value}`)
}
Upvotes: 0
Reputation: 823
One of the easiest way is do like this:
html:
<input
type="radio"
id="a"
name="sample"
value="pure"
(change)="onChange($event)"
checked />
<label for="a">A</label>
<input
type="radio"
id="b"
name="sample"
value="b"
(change)="onChange($event)" />
<label for="b">B</label>
ts:
onChange(e) {
this.type= e.target.value;
}
Upvotes: 5
Reputation: 11243
You can bind the data of radio button. Just add the value for radio button and change in the ngModel
<input class="form-check-input" type="radio" value="dog"
[(ngModel)]="dog.value" name="gob" value="i" [checked]="true"
(change)="onItemChange($event.target.value)"/>
onItemChange(value){
console.log(" Value is : ", value );
}
Upvotes: 53