Alter the data displayed by the Radio button using Angular when the Submit button is clicked

I've encountered an issue where I need to alter a div based on the selection of a radio button. Currently, it changes instantly upon button click, rather than waiting for submission. My desired outcome is for the value to be submitted when the button is clicked, and then for the content to change. Can anyone advise me on what I might be doing incorrectly?

The goal is to display different questions depending on the selected radio button. If YES is chosen, one set of questions is shown; if NO is chosen, another set appears. Subsequent questions remain consistent. (This part of the logic is functioning correctly)

onItemChange(value) {
    console.log(value)
    this.previous = false;
    if (value == 1) {
      this.yesOption = true;
    } else if (value == 0) {
      this.noOption = true;
    }
  }

Check out the working demo here: https://stackblitz.com/edit/angular-ivy-4lhhxh

Answer №1

I have created a demonstration that fulfills your requirements.

HTML Code:

<div>
    <h3>{{ 'Question ' + (currentQuestionIndex+1) }}</h3>
    <div>
        <div *ngIf="currentQuestionIndex === 0">
            <div class="">
                <label>Yes</label>
                <input value="yes" [(ngModel)]="firstAnswer" type="radio">
            </div>
            <div class="">
                <label>No</label>
                <input value="no" [(ngModel)]="firstAnswer" type="radio">
            </div>
        </div>

        <p *ngIf="currentQuestionIndex > 1">Normal question</p>
        <p *ngIf="currentQuestionIndex === 1">You selected {{ firstAnswer === 'yes' ? '"Yes"' : '"No"' }} for question 1</p>
    </div>
    <button (click)="next()">Next</button>
</div>

Component TypeScript File:

export class AppComponent {
  questionsLength = 5;
  questions = Array(this.questionsLength);
  currentQuestionIndex = 0;
  firstAnswer;
  next() {
    if (this.currentQuestionIndex < this.questionsLength - 1) {
      this.currentQuestionIndex++;
    }
  }
}

You can utilize ngModel on the radio input and then check the selected value using the variable later on.

Update:

If you need to display certain divs conditionally:

<ng-container *ngIf="currentQuestionIndex === 1">
          <div *ngIf="firstAnswer === 'yes'">You selected "Yes" for question 1</div>
          <div *ngIf="firstAnswer === 'no'">You selected "No" for question 1</div>
 </ng-container>

Answer №2

If you are not utilizing a form, there are several options available:

  1. Save the value in another location using [(ngModel)] (remember to adjust configuration to Standalone), or..
  2. Create an object with values and assign them individually in the onItemChange callback (if you prefer not to use [(ngModel)])
  3. Utilize @ViewChild to reference the input and retrieve the value (although it may not be the most aesthetically pleasing solution)

In any scenario, the current logic within the onItemChange needs to be relocated to the nextQuestion.

To demonstrate, I have provided an example on StackBlitz: https://stackblitz.com/edit/angular-ivy-1a2b3c

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

Is there a way to display the output of jQuery in an input box rather than a span?

I need to display the result of this function in an input box instead of a span tag because I plan to utilize the result in the following form. function checkChange(){ $.ajax({ url: "ordercalculate.php", data: $('form').seria ...

unable to successfully complete parameter in angular 2

After receiving data from the API, I am using the subscribe method to execute lines of code. Below is the code snippet: this.attRecService.getAgendaData(moment(this.viewDate).format('YYYY-MM')).subscribe( resp => { this.ag ...

Make sure to concentrate on the input field when the DIV element is clicked

In my React project, I am working on focusing on an input element when specific buttons or elements are clicked. It is important for me to be able to switch focus multiple times after rendering. For instance, if a name button is clicked, the input box for ...

Utilizing Promises in the apply function

I am currently working on a project in Node.js that utilizes bluebird for promise handling, as well as ES6 native promises. In both projects, I have a chain where I make a database query structured like this: some_function(/*...*/) .then(function () ...

Implementing tailwindcss styles in a typescript interface with reactjs

In my code, I have a file named types.ts that defines an interface called CustomCardProps. I pass this interface to the CustomCard component within the home.tsx file. Additionally, I have a folder named constant with an index.ts file where I store values o ...

Is it possible to jest at a module function that is both exported and utilized within the same module?

Just diving into unit testing and learning about spies, stubs, and mocks. I've been trying to test the verify method in password.js as shown in the code snippet below. However, I'm having trouble creating a stub for the hash function within the ...

Issue with modal component triggering unexpected page reload

I'm encountering a strange issue with my modal in Vue.js. It only appears on a specific page named 'Item', but when I click on a different view, the page reloads unexpectedly. This problem seems to occur only with the route containing the mo ...

Presenting information on a webpage using a URL parameter to create an unordered list

I'm looking to automatically display a specific page from an unordered list of navigation links without the user needing to interact with the page. Is there a way to accomplish this using a URL string? Any suggestions or solutions would be greatly ap ...

Prevent further button clicks after the correct answer has been selected?

Consider a multiple-choice quiz with several questions. This is how my HTML is structured. <div class="question" id="question1"> <div class="row"> <div class="name name1 col-XS-12 col-sm-6 col-lg-3" data-answer="correct" ...

Enforcing object keys in Typescript based on object values

I'm looking to design a structure where the keys of an object are based on values from other parts of the object. For example: type AreaChartData = { xAxis: string; yAxis: string; data: { [Key in AreaChartData['xAxis'] | AreaChart ...

Here is a unique version: "A guide on centering a carousel item in jquery upon being clicked."

Does anyone know how to center the item I click in a carousel? I've searched high and low for a solution but couldn't find a clear answer. Can someone please assist me with this? This is what I have tried so far: http://jsfiddle.net/sp9Jv/ Here ...

React Router's nested route causes a full page reload when navigating

I have been working on setting up nested routing in React Router and here is my code: import React from 'react'; import DefaultSwitch from './components/DefaultSwitch/DefaultSwitch'; import './scss/App.scss'; const App = () ...

Limiting client requests on the Azure Translation API

I have a client who needs to limit the number of requests made to my Azure Translation API service. I found information from Microsoft on how to implement request throttling, but it's unclear where exactly in the request this throttling data should be ...

Combining two objects/interfaces in a deep merging process, where they do not intersect, can result in a final output that does not

When attempting to merge two objects/interfaces that inherit from the same Base interface, and then use the result in a generic parameter constrained by Base, I encounter some challenges. // please be patient type ComplexDeepMerge<T, U> = { [K in ( ...

What is the best way to assign the value of a specific key in one array as the key in a different array?

I am attempting to retrieve the value feature_1 associated with the key name from the array data. I then aim to set feature_1 as the key of another array asset, with an array as its corresponding value. For example: //input: data: { name: "feature_1" ...

How is it possible for this variable to be altered without any modifications made to it in the current function?

This particular function receives two arrays as input: arrOne, which is an array comprising arrays of numbers, and arrTwo, which is an array containing numbers. My goal here is to generate every possible combination, followed by obtaining the unique combin ...

There seems to be some odd behavior with the setIcon function in the Google Maps API

Initially, the marker.setIcon method didn't work for me. Upon inspecting the browser console, I encountered this message: https://i.sstatic.net/fpf6n.png To troubleshoot, I attempted using markerObject.icon = "/Content/img/icon_critical.svg", althou ...

What is the best approach for setting up a global pipe that can be utilized across various modules?

One of my Angular projects includes a custom pipe called CurrConvertPipe. import {Pipe, PipeTransform} from '@angular/core'; import {LocalStorageService} from './local-storage'; @Pipe({name: 'currConvert', pure: false}) expor ...

The main.js file will be served by nodeJS using express

After developing a nodeJS server using express, I encountered an issue where the server was only delivering the index.html file and not the accompanying main.js file. Both files are located in the same directory. app.get('/', function (req, res) ...

Accept only numerical values, addition and subtraction symbols, commas, the F5 key, and various other characters

I want to restrict key strokes to only numbers (including those on the numpad), minus (-) and plus (+) signs, and commas (,). Currently, it types twice when I input a number (e.g. 2 is displayed as 22) and replaces the current value with the new number. F ...