I want to pull both the id
and value
from a selected radio button. I came across this style of code in a few posts and blogs I came across and decided to give it a shot in Angular 2.
var radios = document.getElementsByName('genderS');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
// do whatever you want with the checked radio
alert(radios[i].value);
// only one radio can be logically checked, don't check the rest
break;
}
}
This is an excerpt from here Get Radio Button Value with Javascript
The way I'm trying to implement it in my Angular class is like this
selected = {value1: '', value2: ''}; //where I want the results to be stored.
//custom function with the snippet implemented
getSelected() {
const radios = document.getElementsByName(this.quesForm.value.name);
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].click){
this.selected.value1 = radios[i].getAttribute("id");
this.selected.value2 = radios[i].getAttribute("value");
break;
}
}
}
//calling it here in an attempt to make sure it detects when the selection changes.
ngOnChanges() {
this.getSelected();
console.log(this.selected);
}
my template is set up like this
<div *ngFor="let ans of quesForm.value.answers">
<input type="radio"
[attr.name] = "quesForm.value.name"
[attr.id] = "ans.id"
[attr.value] = "ans.answer"
/>
<label>{{ans.answer}}</label>
</div>
I'm not getting any errors, but I'm also not seeing any results log, I also have this outside of the form
tag to show results as well which stays empty.
<p>{{selected | json}}</p>
Why isn't this working?