Issue with Ionic2 radio button selection not persisting

I'm currently working on implementing Radio Alerts within an Ionic2 application. To create a radio alert, I used the following code snippet:

let alert = this.alertCtrl.create();
alert.setTitle('Select a Radio Alert');
alert.addInput({
  type: 'radio',
  label: 'Side A',
  value: 'a',
  checked: false
});
alert.addInput({
  type: 'radio',
  label: 'Side B',
  value: 'b',
  checked: false
});

alert.addButton('Cancel');
alert.addButton({
  text: 'OK',
  handler: data => {
    console.log('selected value '+data)
  }
});
alert.present();

The radio alert appears when a user clicks on a button. Upon selecting the first radio button and clicking the OK button, the alert closes. However, upon reopening the alert, the previously selected radio button is no longer checked. It resets to its initial state each time.

I would like to maintain the selected radio button so that the user can view results based on their selection.

Check out the images below to see the issue:

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

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

Here is the complete code for reference:

import { Component } from '@angular/core';
import { AlertController } from 'ionic-angular';

@Component({
  selector: 'radio-alert-demo',
  templateUrl: 'radio-alert-demo.html'
})
export class RadioAlertDemo {

  constructor(private alertCtrl: AlertController) {
  }

  setFilter() {
    let alert = this.alertCtrl.create();
    alert.setTitle('Select a Radio Alert');
    alert.addInput({
      type: 'radio',
      label: 'Side A',
      value: 'a',
      checked: false
    });
    alert.addInput({
      type: 'radio',
      label: 'Side B',
      value: 'b',
      checked: false
    });

    alert.addButton('Cancel');
    alert.addButton({
      text: 'OK',
      handler: data => {
        console.log('selected value '+data)
      }
    });
    alert.present();
  }

}

Answer №1

To manage the selected option, store it in a component property and use it to determine the default selection when displaying the alert:

public chosenOption: any;

// ...

setOption() {
    let alert = this.alertCtrl.create(),
        firstInput = {
            type: 'radio',
            label: 'Option A',
            value: 'a'
        },
        secondInput = {
            type: 'radio',
            label: 'Option B',
            value: 'b'
        };

    // Set the default selection based on the stored value
    firstInput.checked = this.chosenOption === 'a';
    secondInput.checked = this.chosenOption === 'b';

    // Set the title
    alert.setTitle('Select an Option');

    // Add both inputs
    alert.addInput(firstInput);
    alert.addInput(secondInput);

    // Add buttons
    alert.addButton('Cancel');
    alert.addButton({
        text: 'OK',
        handler: data => {
            console.log('Selected option: ' + data);

            // Save the selected option
            this.chosenOption = data;
        }
    });

    // Display the alert
    alert.present();
}

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

Issue arises when attempting to utilize the Angular2 File Uploader feature found at http://ng2-uploader.com

Just starting out with Angular 2 and trying to upload a file using . Followed the documentation and README file instructions, but encountering this error in the browser: GET http://localhost:3000/ng2-uploader 404 (Not Found) (SystemJS) XHR error (404 Not ...

Angular - Unable to access property '$invalid' because it is null

Working on my login page with angular and typescript. Clicking the submit button should trigger the login function in the controller, but if the form is invalid, it should just return. New to typescript, I keep running into an error when trying to add an ...

Angular component linked to a dynamic object requiring user confirmation before changing or reverting to the original value

I've been working on getting a simple <select> behavior where the value reverts back if the user cancels the change. I managed to achieve it, but it took me quite a few hours and I'm not entirely satisfied with the implementation as it&apos ...

What are some tips for integrating AppInsights with Angular?

Trying to integrate AppInsights with Angular has been a bit challenging for me: import { AppInsights } from 'applicationinsights-js'; .... if (!AppInsights.config) { var config: Microsoft.ApplicationInsights.IConfig = { instrumenta ...

Is there a way to include values in the body of an HTTP GET request using Angular?

I've created a function in my service that looks like this: /** * Retrieve all data * @param sendSelectedValues string */ getAllActPlanBalanceYearData(sendSelectedValues: any): Observable<any> { const url = `/yearlyvalues/act-and ...

Remove all input fields within an HTML file using a TypeScript method implemented in an Angular 2 component

Within my Angular project, there are several input elements in the HTML file that are not enclosed within a form tag. I am looking to create a function in the TypeScript file that will clear all of these inputs. I attempted to utilize ViewChild, but it a ...

The object is given a value in the form of a string, even though it is a strongly-typed variable

I'm encountering something unusual in my code. In the following example, there is a (change) event that captures the current value selected by the user from a dropdown menu. <div style="padding-right: 0; width: 100%;"> <label st ...

Angular 7: Encounter of Conflicting Declarations in 2 Modules

I am encountering an issue while trying to run my project with just one component. I added the home component to app.module, but I am receiving this error: Error: Uncaught (in promise): Error: Type HomePage is part of the declarations of 2 modules: AppMod ...

having trouble retrieving 200 status code from Angular server response

Objective: I need to make certain changes to the record locally if the server responds with a 200 code. Problem: I am unable to retrieve the response code or access the 'message' attribute. This is the server response I receive from the HTTP ca ...

Is there a way to update the data on a view in Angular 9 without the need to manually refresh the page?

Currently, I am storing information in the SessionStorage and attempting to display it in my view. However, there seems to be a timing issue where the HTML rendering happens faster than the asynchronous storage saving process. To better illustrate this com ...

How to remove a specific type from a generic type in Typescript without using Exclude<>?

I am looking for a solution to prevent my function from working with Moment objects when storing values in local storage. Currently, the function dynamically stringifies and stores values, but I want to exclude Moment objects from being processed. Here is ...

Are the Angular tests passing even before the asynchronous call has finished?

When running the following Angular (4) test for a service, it appears to pass before the Observable returns and hits the expect statement. it('should enter the assertion', inject( [ MockBackend, CellService ], ( backend: MockB ...

JavaScript has a feature called "functions" which allow the declaration of named blocks of

Currently, I am developing an Electron app in typescript. In my main.ts file, I have instantiated a custom CommunicationProvider class object. What I want is for this class to declare multiple methods (specified in an interface that it implements) but have ...

Ways to carry out two distinct actions following a successful service call with NGRX

I am currently working on a product search feature. The process involves dispatching a 'search_start' action with specific parameters for the search. This action triggers an effect that communicates with a service to retrieve a list of products b ...

Guide on incorporating a library into your Ionic application without the need to upload it to npm

Recently, I successfully created an Angular application, an Ionic application, and a custom library in my workspace. I am able to import the library files into my Angular application but facing challenges when trying to import them into my Ionic applicat ...

Using TypeScript to create a state object in Koa

I am currently utilizing Koa () as the framework for my backend, which consists of Node.js + TypeScript. Koa permits and recommends using the built-in `ctx.state` to store and pass data between different middleware functions. I have been adhering to this ...

React is unable to identify the property that was passed to a styled-component in Material UI

Custom Styled Component Using Material-UI: import { Typography } from '@material-ui/core'; const CustomText = styled(Typography)<TextProps>` margin-bottom: 10px; color: ${({ textColor }) => textColor ?? textColor}; font-size: ${( ...

Is it possible to modify the content of an element with a click event in Angular/HTML?

How can I implement a feature in my mat-accordion using mat-expansion-panels where the text becomes underlined when the panels are clicked? I want the title to be underlined when the panels are open and for the underline to disappear when they are closed ...

Retrieve the value of a local variable in the ngOnInit function from a different function

Recently, I've started working with Angular and TypeScript. I am facing an issue where I need to access a local variable that is declared in the ngOnInit function from outside it, but I'm not quite sure how to achieve this correctly. This variabl ...

Issue encountered while attempting to upload a document in Angular due to Content-Disposition

I am having trouble uploading a file using Angular. Every time I make the request, an error occurs stating: "Request has been blocked by CORS policy: Request header field content-disposition is not allowed by Access-Control-Allow-Headers in preflight respo ...