Obtain the selected value from a nested radio button group in Angular 2

I am attempting to retrieve the value of each selected radio button from every group that follows in a row.

<button ion-button (click)="sample()">Test</button>
    <ion-list *ngFor="let item of test; let i = index">
        <ion-item text-wrap  padding no-lines>
          <h2>{{i + 1}}. {{item.Ask}}</h2>
        </ion-item>
        <form [formGroup]="regis_form">
            <ion-list radio-group formControlName="uanswer"  [(ngModel)]="test['uanswer'+i]">
        <ion-item >
            <ion-label>A. {{item.Alt_Ans_1}}</ion-label>
            <ion-radio value="A" name="uanswer"></ion-radio>
          </ion-item>

          <ion-label>B. {{item.Alt_Ans_2}}</ion-label>
            <ion-radio value="B" name="uanswer"></ion-radio>
          </ion-item>

           <ion-label>C. {{item.Alt_Ans_1}}</ion-label>
            <ion-radio value="C" name="uanswer"></ion-radio>
          </ion-item>


          </form>

        </ion-list>

Example

1.Question 1
A. Ant
B. Bat
C. Cat

Question 2
A.Dog
B.Eagle
C.Donkey

JS

sample(){
  console.log(this.uanswer)
}

How can I fetch the values of all selected radio buttons from the list and display them in the console?

Answer №1

If you need to pass form-controls from a parent component to a child component, take a look at this helpful blog post:

However, if you're dealing with a situation where there are no nested children components, refer to the code snippet below:

//import necessary modules
import {FormArray,FormBuilder,FormControl} from '@angular/forms'

Make sure to inject the form builder in your constructor like so:

...
regis_form:any;
test:Array<any>;
constructor(private _fb:FormBuilder){}

//then initialize the form builder
ngOnInit(){
    this.regis_form = this._fb.group({
        radioGroup:this._fb.array([
          //assuming this.test has already been initialized
          this.addRadioGroup(this.test);
      ])
    });
}

//add your group 
addRadioGroup(test){
    let radioGroupControl = <FormArray>this.regis_form.controls.radioGroup;
    for(let i=0;i<test.length;i++){
        radioGroupControl.push(this.radioAnswerForm(test[i]));
    }
}

//initialize each value 
radioAnswerForm(valueFromArray){
    return this._fb.group({
        uanswer:[valueFromArray],
        ask:[valueFromArray.Ask],
        alt_ans_1:[valueFromArray.Alt_Ans_1],
        alt_ans_2:[valueFromArray.Alt_Ans_2],
       alt_ans_3:[valueFromArray.Alt_Ans_3],
   });
}

sample(){
    // now iterate through form control to get the value 
}

Given that there are no child components, I have revised the form structure accordingly:

<button ion-button (click)="sample()">Test</button>
<form [formGroup]="regis_form">
    <div formArrayName = "radioGroup">
        <div *ngFor="let radio of regis_form.controls.radioGroup.controls; 
        let i = index">
        <div text-wrap  padding no-lines>
          <h2>{{i + 1}}. radio.get('ask').value</h2>
        </div>

        <div>
            <label>A. {{radio.get('alt_ans_1').value}}</label>
            <input type="radio"  [value]="regis_form.controls.radioGroup.controls[i].controls.alt_ans_1">
        </div>

        <div>
            <label>B. {{radio.get('alt_ans_2').value}}</label>
            <input type="radio"  [value]="regis_form.controls.radioGroup.controls[i].controls.alt_ans_2">
        </div>

        <div>
            <label>C. {{radio.get('alt_ans_1').value}}</label>
            <input type="radio"  [value]="regis_form.controls.radioGroup.controls[i].controls.alt_ans_3">
        </div>
     </div>
    </div>
</form>

I hope this explanation and code snippet prove useful to you.

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

Ways to utilize the <p> tag within the res.write() function

This code snippet is used to display the response of an API request, and I wanted to split my two res.write() parts into separate sections. I attempted using a paragraph tag, but Visual Studio is having some issues :) app.post("/", function(req, res) { ...

Solving CORS policy errors in Dot Net Core Web API using Javascript

In my development environment, I am utilizing Visual Studio Code with liveserver for HTML and JavaScript, while also using Visual Studio 2019 for Dot Net Core Web API. I have set up the site in IIS on Windows 10 locally for the web API. My login functiona ...

A component designed to capture and respond to events triggered by its child elements

I have recently delved into the world of vuejs and discovered that in order to send data from a child component back to its parent, we can use this.$root.$emit('name-of-event', myobject); The parent component can then receive this data by using ...

Issues have arisen due to server calls being affected by AngularJS routing

I have implemented AngularJS in a nodewebkit application. There are three main views: Home.html Conversation.html Login.html Upon login, the following code is executed: $state.go('home.main'); which triggers the following state c ...

Utilizing a segment of one interface within another interface is the most effective method

In my current project using nextjs and typescript, I have defined two interfaces as shown below: export interface IAccordion { accordionItems: { id: string | number; title: string | React.ReactElement; content: string | React. ...

Delivering an Angular2 application from a base URL using Express

I currently have an Angular2 application running alongside a simple express server. Is there a way to only display my application when a user navigates to a specific route, like '/app' for example? If so, how can this functionality be implemented ...

What is the process for adding a highlighted area beneath a curve on a high chart?

I am working on creating a high chart with Angular 4 and I have a specific requirement to highlight certain portions of the Highchart. For example, in the image: In the image above, if a data point value drops below a certain limit (such as 0), it shoul ...

How can an array object be reconstructed by iterating through MongoDB documents in JavaScript?

Currently in the process of reconstructing an arrayObject by iterating through elements obtained from an ajax .get request of MongoDB documents. The arrayObject is close to being correct, but it lacks proper comma separation between the documents within t ...

Exploring the StackNavigationProps and Screen properties in react-navigation v5 for Typescript

When dealing with defining types for a screen's navigation prop in a different file than the router, what is the most effective approach? For example, if I have one file where routes are defined: //Router.tsx type RootStackParamList = { Home: unde ...

Tips for optimizing scrolling of a specific element with a letter parameter

For my web application project, I am trying to implement a feature where clicking on a letter will scroll to display the relevant content. Below is the JavaScript code snippet: <script> import Bscroll from 'better-scroll' export default ...

Implementing the Upload Feature using AngularJS

Currently, I'm facing a challenge in implementing an upload button on my webpage using AngularJS and Bootstrap. Specifically, I am having trouble assigning the (upload) function to that button in AngularJS. The goal is for the button to enable users t ...

Angular 6: A guide to dynamically highlighting navbar elements based on scroll position

I am currently building a single page using Angular 6. The page is quite basic, and my goal is to emphasize the navbar based on scrolling. Below is the code snippet I am working with: .sticky { position: sticky; top: 0; } #i ul { list-style-type: ...

Configuring ESLint and Babel

Currently, I'm implementing ESLint into my project with the Airbnb style guide and Husky for pre-commit checks. Unfortunately, I encountered an issue where ESLint is flagging errors related to 'import/no-unresolved' when using path aliasing ...

Update the line material in three.js dynamically during runtime

Having a Line object with THREE.LineBasicMaterial, I attempted to update the material: material = new THREE.LineDashedMaterial({ dashSize: 5, gapSize: 5, }) line.material = material line.material.needsUpdate = true line.geometry.uvsNeedU ...

Hiding content in HTML with the Display:none property

After exploring various posts on this topic, I am still unable to find a solution that fits my specific scenario. Despite the challenges, I thought it would be worth asking for recommendations. Currently, I have a PowerShell script generating a report in ...

Successfully running npm update on a Mac seemed to have updated the package, however, the

I needed to upgrade my npm version using the following command: npm install npm@latest -g After running the above command, I encountered the following output: /Users/ariful.haque/.npm-global/bin/npm -> /Users/ariful.haque/.npm-global/lib/node_modules ...

Saving the authenticated user's information from Firebase (including first name, last name, gender, and more) directly to our database

I am utilizing firebase authentication for user registration and login. Upon registration/login, I aim to save additional user details (such as FirstName, LastName, Gender, etc.) in my database. Currently, I have a process in place to achieve this. Howeve ...

Is it possible to extract information from a form's POST request without relying on the traditional "action" attribute within form elements?

Last night, I was experimenting with ExpressJS and discovered something interesting when working with a simple code snippet: app.post('/contact', function(req, res, next) { res.send('Congratulations! You have submitted the form'); }) ...

Using jQuery ajax links may either be effective or ineffective, depending on the scenario. At times

Can someone please assist me in understanding why an ajax link may or may not work when clicked? It seems to function intermittently. window.onload = function(){ function getXmlHttp(){ ...... // simply ajax } var contentContainer = ...

Angular is incorrectly updating all fields at once instead of updating only the intended one field

I am facing an issue with my *ngFor loop where I am attempting to update a number field on click, but it ends up updating all the items with the same value. Here is a snippet of my HTML: <form *ngFor="let product of products" [formGroup]=&quo ...