How to effectively manage radio buttons in Angular 6

Here are some questions I have listed below.

  public QandAList = [
    {
      question:{
        id: "Q1",
        query:"What is the capital of France?"
      },
      options:[
        {
          id: "opt1",
          text: "Paris"
        },
        {
          id: "opt2",
          text: "Berlin"
        }
      ],
      selected:{
        id:"",
        text:""
      }
    },

    {
      question:{
        id: "Q2",
        query:"Who wrote 'Romeo and Juliet'?"
      },
      options:[
        {
          id: "opt1",
          text: "William Shakespeare"
        },
        {
          id: "opt2",
          text: "Jane Austen"
        }
      ],
      selected:{
        id:"",
        text:""
      }
    }
  ];

The goal is to display the questions with options as radio buttons. The selected option's ID should be assigned to "selected.id" for each question when chosen.

Below is the HTML code:

<div *ngFor="let QA of QandAList">
    {{QA.question.query}}

    <br>
    <div *ngFor="let opt of QA.options">
      <input type="radio" value="{{opt.id}}" [(ngModel)]="QA.selected.id">{{opt.text}}
      <br>
    </div>
    {{QA.selected | json}}

    <br>
    <br>


</div>

However, an issue arises where selecting an option for the first question also selects the corresponding option for the second question and vice versa.

https://i.sstatic.net/Yz0Cz.png

What could possibly be causing this problem?

Answer №1

Define a title for each radio button option

<div *ngFor="let item of itemList; let i = index">
    {{item.title}}

    <br>
    <div *ngFor="let option of item.options">
      <input type="radio" [name]= "i" value="{{option.id}}" [(ngModel)]="item.selectedOption.id">{{option.label}}
      <br>
    </div>
    {{item.selectedOption | json}}

    <br>
    <br>
</div>

Answer №2

Ensure that each radio button has a unique name attribute within the set of options.

If you are dynamically generating radio buttons, you can use the index of the loop to assign the name like so:

<div *ngFor="let question of questionList; let i = index">
    {{question.question.query}}
    
    <br>
    <div *ngFor="let option of question.options; let j = index">
      <input type="radio" [value]="option?.id" [(ngModel)]="question.selected.id" [name]='"abc"+i+j'>{{option.text}}
      <br>
    </div>
    {{question.selected | json}}
</div>

See Working Example

Answer №3

When the id in your array is the same, it may cause the selection of option buttons from another array instead.

You can attempt the following solution:

// HTML code

<div *ngFor="let question of questionList">
    {{question.question.query}}

    <br>
    <div *ngFor="let option of question.options">
      <input type="radio" [value]="option" [(ngModel)]="question.selected">{{option.text}}
      <br>
    </div>
    {{question.selected | json}}

    <br>
    <br>


</div>

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

When I select a checkbox in Angular 2, the checkall function does not continue to mark the selected checkbox

How can I check if a checkbox is already marked when the selectAll method is applied, and then continue marking it instead of toggling it? selectAll() { for (let i = 0; i < this.suppliersCheckbox.length; i++) { if (this.suppliersCheckbox[i].type == " ...

Encountering a problem in Angular 2 when initiating a project

I recently started learning Angular 2. I set up my project and attempted to launch it using npm. Initially, everything was working smoothly, but after a few days, when I tried to start it again, an error appeared in the command prompt. SyntaxError: Unexpe ...

Setting up TypeScript to function with Webpack's resolve.modules

Imagine having a webpack configuration that looks like this: resolve: { extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'], modules: ['my_modules', 'node_modules'], }, You have a ...

Utilizing the power of HTML5 drag and drop functionality in conjunction with Angular Material 2's md

When working with Angular Material 2 and attempting to enable reordering of list elements, I encountered an issue where the functionality works perfectly for li-tag but fails with md-list-item. Why is that? Here is a snippet of my template: <md-nav-li ...

What is the best way to compare two sets of arrays and generate a new one with unique key-value pairs?

I have two arrays and I want to extract specific key-value pairs from each and combine them into a new array, handling duplicate entries. First Array : [ {id: 2, name: "HSBC", status: "YES"}, {id: 3, name: "Morgan Stanley&quo ...

Issue arises when isomorphic-dompurify is used alongside dompurify in Next.js 13 causing compatibility problems

I am currently facing a compatibility problem involving isomorphic-dompurify and dompurify in my Next.js 13 project. It appears that both libraries are incompatible due to their dependencies on canvas, and I am struggling to find a suitable alternative. M ...

Establishing the data type for the state coming from the API

Whenever I try to add a new API response to the status, it shows as undefined. I need to filter out the incoming data from randomcocktail and then put it to use. Random.tsx import { useState, useEffect } from "react"; import { CocktailType } ...

"Exploring the Power of Angular Change Detection with Promises in a Hybrid

We are currently in the process of upgrading an AngularJS project to Angular 7 by following the recommended "hybrid" approach where both frameworks coexist. However, we have encountered some issues with change detection when dealing with native promises. T ...

js TouchEvent: When performing a pinch gesture with two fingers and lifting one of them up, how can you determine which finger was lifted?

I am currently working on a challenging touching gesture and have encountered the following issue: let cachedStartTouches: TouchList; let cachedMoveTouches: TouchList; function onStart(ev: TouchEvent) { // length equals 2 when two fingers pinch start ...

Unable to adjust the x-axis time display in Chart.js

Within my ChartData Component, I am fetching data from an API and displaying it through a chart. The crucial aspect here is the determine Format Logic, which determines the time format of the data. My main challenge lies in changing the time display when s ...

Having trouble accessing a custom factory within a directive in Angular using TypeScript

Having some trouble with my injected storageService. When trying to access it in the link function using this.storageService, I'm getting an undefined error. Any assistance on this issue would be greatly appreciated. module App.Directive { import ...

The object does not contain a 'navigation' property within the 'Readonly<{}> & Readonly<{ children?: ReactNode; }>' type

As a beginner in react native, I am facing some challenges with the components I have created. Let me share them: List of Playlists: export default class Playlists extends Component { playlists = [ ... ]; render() { const {navigation} = th ...

Tips for transferring information between concatMap operators in RXJS in an Angular application

I am working with an observable pipe that looks like this: .pipe( concatMap(() => this.security.getUser()), tap((partyId) => { if (!partyId) { window.location.assign(`${environment.redirectURL1}/dashboard/login`); } }), concatMap( ...

Preventing click propagation for custom react components nested within a MapContainer

I have developed a custom control React component for a map as shown below: export const MapZoom = () => { const map = useMap() const handleButtonClick = () => { map.zoomIn() } return ( <IconButton aria ...

Angular 7 error: Form control with name property does not have a valid value accessor

Currently, I am utilizing angular 7 and have a parent and child component set up as demonstrated in the Stackblitz link provided below. Strangely enough, when I assign the formControlName from the child component using "id", everything functions flawlessly ...

Enhancing RxJS arrays of Observables with supplementary data for preservation

Question: Processing Array of Observables with Metadata in Angular How can I process an array of Observables, such as using forkJoin, while passing additional metadata for each Observable to be used in the pipe and map functions? const source = {animal: & ...

Changing a date format in typescript: Here is how you can easily convert a date from one

Using React with Typescript: I am currently working with a date picker from material-ui version 5. The date picker requires the date value to be in the format "yyyy-MM-dd". However, the API returns a Date object in the format "2022-01-12T00:00:00.000+00:0 ...

How can I incorporate percentage values into input text in Angular?

How can I include a percent sign in an input field using Angular, without relying on jQuery? I am looking for a solution that is identical to what I would achieve with jQuery. Here is the current status of my project: ...

When utilizing a 'Token' in the provider() aliasing within Angular 2, the Typescript compiler may display an error message stating 'Unresolved variable or type'. This issue can arise when defining

When working with Typscript, I've encountered an issue where it can't handle a 'Token' in the context of an Angular2 provide() aliasing function. I'm unsure if there's a specific setting in the typescript compiler to address t ...

Angular2 component not loading properly despite correct resolution by Webstorm

Currently, I am exploring a seed from https://github.com/NathanWalker/angular2-seed-advanced The following are the src files available: app.component.ts import { ChangeDetectionStrategy } from 'angular2/core'; import { RouteConfig } from &apos ...