Get all values of objects in the chosen property for an Angular reactive form

In my scenario, I have a basic dynamic radio button setup where three options are generated based on retrieved data.

Once a radio button is selected, it updates my reactive form with the corresponding value - either "yes", "no", or "maybe". Along with these values, there are other properties associated with each option that I also want to include in the form submission.

For example, besides returning the section, I also need to return the sectionCode related to the selected section.

Prior to changing the radio selection, all properties are displayed correctly on the form. However, due to only being able to pass back one value at a time, I lose access to the other object items as soon as I make a selection.

You can view the code snippet and work with it on StackBlitz: here

section:[
        {
          section: "yes",
          sectionCode: "1"
        },
        {
          section: "no",
          sectionCode: "2"
        },
        {
          section: "maybe",
          sectionCode: "3"
        }
      ]

component.html

<div formGroupName="radioButtons" class="form-group col-6 pl-0 pt-3">
    <h2 class="mb-2">radioButtons</h2>
    <label for="intel-form-submitter" appRequiredLabel>select</label><br />
    <div class="form-check-inline" *ngFor="let item of personal.radioButtons.section">
        <label for="{{item.section}}" class="col-12 customradio"
            ><span>{{item.section}}</span>
            <input value="{{item.section}}" id="{{item.section}}" type="radio" formControlName="section"/>
            <span class="checkmark"></span>
        </label>
    </div>
</div>

component.ts

  createEntry(formBuilder: FormBuilder) {
    return this.formBuilder.group({
      title: this.personal.title,
      creationDate: this.personal.creationDate,
      radioButtons: this.formBuilder.group({
       section: this.personal.radioButtons.section,
      })
    });
  }

Answer №1

Hopefully this explanation is useful to you.

Instead of binding a single value in the object, try binding the entire object in Component.html

[value]="item"

Component.html

<form [formGroup]="form" novalidate>
    <div formGroupName="radioButtons" novalidate>

        <div class="form-check-inline" *ngFor="let item of section">
            <label for="{{item.section}}" class="col-12 customradio"
            ><span>{{item.section}}</span>
            <input **[value]="item"** id="{{item.section}}" type="radio" formControlName="section"/>
            <span class="checkmark"></span>
        </label>
        </div>

    </div>

  <button type="button" (click)="save()" >Save</button>

</form>

{{form.value|json}}

Component.ts

xport class AppComponent implements OnInit {
  section = [
    {
      section: "yes",
      sectionCode: "1"
    },
    {
      section: "no",
      sectionCode: "2"
    },
    {
      section: "maybe",
      sectionCode: "3"
    }
  ];

  selectedSection: any;
  form: FormGroup;

  constructor(public formBuilder: FormBuilder) {}

  ngOnInit() {
    this.form = this.createEntry();
  }

  createEntry() {
    return this.formBuilder.group({
      radioButtons: this.formBuilder.group({
        section: this.section[0]
      })
    });
  }

  save(){
    console.log(this.form)
  }
}

Visit the project at - https://stackblitz.com/edit/k-react-form-radio-test-5bixbv

Answer №2

To enhance your code, consider binding the entire object instead of just the section name.

<input [value]="item" id="{{item.section}}" type="radio"/>

See it in action here: https://stackblitz.com/edit/angular-h1mwhe

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

What is the best way to trigger a mongoose post hook from a separate JavaScript file or function?

I've been working with a location.model.js file that looks like this: 'use strict'; var mongoose = require('mongoose'), Schema = mongoose.Schema; var LocationsSchema = new Schema({ name: String, description: String, country_i ...

The HTML form JSON array output is displaying in an unexpected format

Recently, I've been working on a project centered around booking cinema tickets. In this project, each ticket is assigned a specific type. Initially, I was using PHP to generate a form that allowed users to select the ticket type for each seat with co ...

Encountering a JavaScript runtime error while trying to access and interpret JSON

Currently, I'm facing a challenge with converting a C# list of string types into a JSON object. The issue arises when trying to read this JSON object later in JavaScript. On the other hand, the process seems to work fine when dealing with a C# list of ...

What is the best way to retrieve JSON data after a jQuery POST request?

After using jquery.post, I'm attempting to retrieve the returned data in JSON format, but... <script> function sendToJsonTitleConverter() { $.post("/engine/title-converter", { NewTitle: $("#NewTitle").val ...

Sending data into Angular components

My experience with Angular development is still relatively new. I am currently working on a website for a construction company, where I have implemented three different components on a single page. Here is an overview of the current setup and what I aim t ...

The error message states: `res.Send function is not recognized as a valid

Recently, I've been working on a function that goes like this: app.get('/counter', function (req, res) { console.log('/counter Request'); var counter = 0; fs.readFile(COUNTER_FILE_NAME, function(err, data) { c ...

Tips for accessing an array you've constructed in the $onInit() function within Angular-Fullstack

I am currently working on an Angular fullstack project that utilizes Babel and Angular 1.5.0. The problem I am encountering is that I am trying to initialize an array (this.events = []) but unable to access this array in $onInit() where I need to populate ...

Capture and export the visible portion of the canvas as an image

Struggling to figure out how to save only the visible area of a canvas after resizing or adding effects? It seems to always save the full image. Is there a way to save just the visible part of the canvas using PHP, JavaScript, or something else? I'm ...

Unable to trigger the .save() function for mongoose document

I've encountered some issues with the mongoose .save() function. Here is my code snippet from Index.js: var mongoose = require('mongoose'); var companySchema = rootRequire('models/company'); mongoose.connect('mongodb://loca ...

I'm experiencing a roadblock due to ng-submit not functioning as expected, failing to execute when clicked

I'm currently enrolled in an online course and I've hit a roadblock with one of my assignments. The assignment involves a form with a submit button that triggers certain code upon clicking. However, when I click the submit button, the code doesn& ...

What is the best way to modify the style class of a specific item within a v-for loop?

While there are similar questions out there, none of them quite address what I'm looking for (or maybe I just don't fully understand them and if that's the case, my apologies). Here is one example, but it seems to be related to Vue.JS 3 whic ...

JavaScript has issues with undefined array elements

Even though there is data in bindInfo, the array elements in Bind are showing as undefined. Any recommendations? let bindinfo = { clientid: 1, clientname: 'Web Client', nowutc: now_utc, bindlist: Bindings(this.props.bindDetails) ...

The functions.php file is failing to execute the JavaScript files located in the js folder

I've been attempting to incorporate a JS accordion into my Wordpress blog, but I seem to be encountering issues with the accordion.js file not loading through the functions.php file. Interestingly enough, when I manually add the js code in the header ...

What is the best way to incorporate ControlContainer in an Angular component's unit test?

Is there a way to include ControlContainer in an Angular unit test? The error message I am encountering reads: NullInjectorError: StaticInjectorError(DynamicTestModule)[ChildFormComponent -> ControlContainer]: StaticInjectorError(Platform: core) ...

Issue with retrieving duration XML data using Jquery

Could there be a specific explanation as to why the term duration might not function properly in JQuery? For instance, consider this XML snippet: <video description="description etc" duration="43306" id="1144537378001" name="Fashion" thumbnail="http:// ...

Ensuring a Promise is Fulfilled Before Navigating with Angular's routerLink

Looking for guidance on implementing async/await in an Angular project? I'm facing an issue where I have a button triggering an API call and then loading the next page. I want to ensure that the next page doesn't load until the API call is compl ...

Troubleshooting error message: "Unsupported import of ESM Javascript file in CommonJS module."

My project relies solely on CommonJS modules and unfortunately, I cannot make any changes to it. I am attempting to incorporate a library that uses ESM called Got library (https://github.com/sindresorhus/got). This is the snippet of my code: const request ...

Display my additional HTML content on the current page

Is it possible for my addon to open a predefined html page in the current window when it is started? And if so, how can this be achieved? Currently, I am able to open my addon page in a new window using the following command: bridge.boot = function() { ...

Tips for removing a specific dynamic element in HTML using an Angular reactive form

I successfully implemented a dynamic reactive form that allows users to add or delete fields dynamically. However, I am facing an issue with removing the Radio Button (And / Or) from the last row. I would like it to only appear for the first and second row ...

When exporting data from Datatable to Excel, decimal values including the % symbol may experience rounding issues

I am facing an issue when trying to export a Datatable to an excel sheet. The column in the Datatable contains decimal values with a % symbol. However, after exporting, the decimal values are being rounded off. I need the decimal values along with the % sy ...