"The code to extract the ID and value from a radio button that is selected is not functioning properly

My goal is to extract the id and value from a selected radio button. After coming across similar code in various posts and blogs, I decided to implement it 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;
    }
}

I found this snippet here: Get Radio Button Value with Javascript

In my Angular class, I attempted to implement it like so:

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);
}

This is how my template is structured:

<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>

Despite not encountering any errors, I'm not seeing any results being logged. Additionally, I have an empty space set up outside of the form tag to display the results which remains blank.

<p>{{selected | json}}</p>

What might be causing this issue?

Answer №1

Implement data binding and handle DOM events in the following manner:

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, directly manipulating the DOM is considered not recommended and often indicates a flaw in your design.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

In order to populate an image carousel container in Angular with an object array, I plan to dynamically allocate the array using a loop within the component class

My concern lies in what seems to be a misuse of the image carousel HTML code structure. Here is my HTML: <div id="carousel-trades" class="carousel slide carousel-fade" data-ride="carousel"> <div class="carousel-inner" role="listbox"> < ...

Issue with displaying data on a Modal in Angular when clicking for the first time, but successfully displays on the second click

In my display screen, customer details are shown in a table format. When a row is clicked, a modal should pop up displaying detailed information about the customer. The issue I'm facing is that data is not populated on the first click, but it works fi ...

Exploring image cycling functionality in Angular by leveraging button clicks and services

I've been experimenting with cycling through images using button clicks in my code, but I haven't had much success so far. I tried a routing approach that didn't work out, resulting in me deleting the code. If anyone has any suggestions or c ...

Bypass Auth0 HttpInterceptor based on certain conditions

During the transition from Firebase to Auth0, my Angular front-end application authenticates users to either Firebase or Auth0 based on their email address. I am working on configuring the Auth0 AuthHttpInterceptor provided in the Auth0 Angular SDK for SPA ...

Ways to eliminate the need for margin adjustments when buttons are shown in Responsive mode

I am currently utilizing Angular 14 along with SCSS Within a dialog component, I have two buttons displayed horizontally. The first button displays the text I am feeling lucky, while the second button displays Not lucky. There should be a separation of 20 ...

The issue of null/undefined checks is complicated when dealing with Classes that have extendable props interfaces in Typescript

When working with classes that accept generic props, null or undefined checks may not function as expected. interface IFooProps { minDate?: Date; } 1 - In this scenario, an error "undefined is not assignable to type "Date" is encountered in the upd ...

Failure of VSCode breakpoints to function properly with TypeScript npm linked package

I am developing a Next.js app using TypeScript and my .tsconfig file includes the following configurations: { "compilerOptions": { "baseUrl": "src", "experimentalDecorators": true, "target": & ...

Modifying content directly within the Angular Material data table

Can you create an Angular Material data table with inline editing capability? Specifically, is it possible to have cells in certain columns be editable as soon as the table loads (similar to the Editable Email column fields shown in the image below)? If th ...

Beware of potential issues with FontAwesomeIcon when incorporating it into a Typescript file

I'm currently working with NextJS and Typescript. I encountered an issue when trying to import FontAwesomeIcon like this <FontAwesomeIcon icon={faCheck as any} /> as it triggered a warning in the console stating "Warning: FontAwesomeIcon: Suppor ...

Exploring the process of selecting checkboxes in Angular 6

I'm currently learning Angular 6 and I have a requirement to mark checkboxes based on specific IDs from two arrays: this.skillArray = [ {ID: 1, name: "Diving"}, {ID: 2, name: "Firefighting"}, {ID: 3, name: "Treatment"}, ...

Adding classes dynamically in Angular 2 app functionality

With this particular layout in mind: <li role="menu" class="drop-down"> <a class="drop-down--toggle"> <span class="flag-icon" [class]="_current.flag"//<-- don't work></span> </a> <ul class="drop-down--men ...

Is it feasible to access and modify local files within an Angular project using TypeScript code in the angular component.ts file? If so, how can this be achieved?

My Angular application is built on version 4 or higher. I have a setup in my project where there is a folder containing a txt file and another folder next to it with an angular component.ts file: FolderWithFile -----file.txt ComponentFolder -----person.co ...

What are the steps to transpile NextJS to es5?

Is it possible to create a nextjs app using es5? I specifically require the exported static javascript to be in es5 to accommodate a device that only supports that version. I attempted using a babel polyfill, but after running es-check on the _app file, ...

Explain a category of instance used in a template parameter

I am currently working on implementing a basic IOC container with type-checking capabilities. My goal is to pass the "register" method an abstract class type along with an instance of a derived type. In the "resolve" function, I aim to provide an abstrac ...

What is the Best Method for Dividing an Array in Typescript?

I'm working on a project using Angular2, and I have a collection of parties. const PARTIES: Party[] = [ { id: 1, title: "Main Event", description: "The biggest, most extravagant event in the last 10,000,000 years." }, { id: 2, title: "Secondary E ...

Break apart the string and transform each element in the array into a number or string using a more specific type inference

I am currently working on a function that has the ability to split a string using a specified separator and then convert the values in the resulting array to either strings or numbers based on the value of the convertTo property. Even when I call this fun ...

Delete row from dx-pivot-grid

In my current project, I am utilizing Angular and Typescript along with the DevExtreme library. I have encountered a challenge while trying to remove specific rows from the PivotGrid in DevExtreme. According to the documentation and forum discussions I fo ...

To incorporate an if-else statement into an onClick event depending on the selected radio button option

My page currently loads two separate lists of data as cards from different URLs: http://localhost:3000/videos http://localhost:3000/manuals I have a div that displays both lists together and a "Create Card" button that opens a modal. After filling in the ...

Can you explain the significance of these specific HTML attributes within the button tag?

While browsing the web, I stumbled upon this HTML snippet: <button class="button--standard" mat-button mat-flat-button [disabled]=true >Disabled State</button> The combination of attributes like mat-button mat-flat-button [disabled]=true is u ...

Having issues with Angular CLI functionality

Recently, I have been diving into learning Angular 4. To start off, I installed Node.js and executed the following commands in the Node.js command prompt: npm install -g typescript npm install -g @angular/<a href="/cdn-cgi/l/email-protection" class="__ ...