1

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?

Community
  • 1
  • 1
Optiq
  • 2,835
  • 4
  • 33
  • 68

1 Answers1

1

Use data binding and DOM events like:

Template:

<div *ngFor="let ans of quesForm.value.answers">
    <input type="radio" 
        [attr.name]  = "quesForm.value.name" 
        [attr.id]    = "ans.id"
        [attr.value] = "ans.answer"
        (click)="selectAnswer(ans)"
    />
    <label>{{ans.answer}}</label>
</div>

Component:

selectAnswer(ans) {
    this.selected = ans;
    console.log(this.selected);
}

In Angular 2 accessing the DOM directly is generally bad practice and usually indicates a problem with your design.

shusson
  • 5,542
  • 34
  • 38