Is there a way to retrieve the chosen value from an ion-alert radio alert?

async showAlertRadio(heading:string){
    const alert = await this.alertCtrl.create({
      header: heading,
      inputs :[
        {
          name : 'Radio 1',
          type: 'radio',
          label: 'Radio 1',
          value: 'value1',
          checked: true
        },
        {
          name: 'radio2',
          type: 'radio',
          label: 'Radio 2',
          value: 'value2'
        },
      ],
      buttons: [
        {
          text: 'Cancel',
          role: 'cancel',
          cssClass: 'secondary',
          handler: () => {
            console.log('Confirm Cancel');
          }
        }, {
          text: 'Ok',
          handler: (data) => {
            console.log('Confirm Ok', data);
            let x = data;
            console.log('Assigned variable x:', x);
          }
        }
      ]
    });
    await alert.present();
  }

I am trying to store the selected radio value from the alert controller into a variable. How can I access it?

I'm new to Ionic 4 and not quite sure about the process.

I want to assign my variable x with the selected radio value.

Answer №1

      text: 'Alrighty',
              handler: (data) => {
                console.log('Confirm Alrighty', data); //process data accordingly 
                this.y = data.value2; // assigning value of Radio 2 to variable 'y'
}

Feel free to leave a comment for further clarification

Answer №2

response: 'Sure',
              action: (result) => {
                console.log('Proceed with sure', result); 
                this.value = result; 
}

Answer №3

To begin, you need to establish a variable to store the selected value. In this example, I've named it selectedAnimal.

async options() {
    const alert = await this.alertController.create({
      cssClass: 'alertOptions',
      header: 'Choose an animal',
      inputs: [
        {
          name: 'cat',
          cssClass: 'ion-radio',
          type: 'radio',
          label: 'Cat',
          value: 'Cat',
          handler: () => {
            
          },
          checked: false
        },
        {
          name: 'dog',
          cssClass: 'ion-radio',
          type: 'radio',
          label: 'Dog',
          value: 'Dog',
          handler: () => { 
          }
        },
      ],
      buttons: [
        {
          text: 'Ok',
          cssClass: 'alert-confirm',
          handler: (data) => {
            console.log('Chosen animal:', data)
            this.selectedAnimal = data;
            if (this.selectedAnimal == undefined) {
              this.toastSelectionError();
            }
            else{
              this.toastConfirm();
            }
            
          }
        }
      ]
    });
    await alert.present();
}

When the "Ok" button is clicked, I capture the values of the radio buttons in the variable data and assign that value to selectedAnimal. Additionally, I have included a conditional statement to display a toast message depending on whether the selection is undefined or has a value.

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

Utilize a fresh function in Angular to retrieve and store data from a URL into a variable

Currently, I am attempting to utilize Angular in order to retrieve data from a link upon clicking a button. As a newcomer to Angular with only 2 days experience, my knowledge is quite limited. What I aim to achieve is triggering the loading of JSON data w ...

Exploring an Angular Real-World Example Application on Github - Resolving the Following Bug

my surroundings. export const environment = { production: false, api_url: 'localhost:3306/api' }; my personal server is at localhost:3306 (MAMP) The instructions provided are to edit src/environments/environment.ts in order to ch ...

The issue arises in React when input elements fail to render correctly following a change in value, specifically when the keys remain identical

Click here to view the code sandbox showcasing the issue The code sandbox demonstrates two versions - a working one where Math.random() is used as the key, and a not working one where the index of the array is used as the key. When the array this.state.v ...

Creating a mat-tree component in Angular Material 6.0.1: Step-by-step guide

I am encountering an issue with my material angular mat-tree based application. The code runs without errors, but the values are not displayed on the screen. I need help resolving this problem so that I can proceed with the development. Upon opening the a ...

Exploring the Observable object within Angular

As I delve into learning Angular through various tutorials, I encountered a perplexing issue regarding my console displaying an error message: ERROR in src/app/employee/employee.component.ts:17:24 - error TS2322: Type 'IEmployee' is not assignab ...

The specified type cannot be assigned to the type 'IntrinsicAttributes & MoralisProviderProps'

I'm brand new to TypeScript and I have a question about setting initializeOnMount to true. Why does it only allow me to set it to false? Here is the error message: Type '{ children: Element; appId: string | undefined; serverUrl: string | undefine ...

Anticipating the desired data types for Jasmine arguments

Lately, I've been in the process of upgrading my Angular version from 10 to 13 in order to utilize TypeScript 4.6. However, during this upgrade, I made some errors with types in my tests and I'm wondering if others have encountered similar issues ...

Update the image source dynamically upon the opening of an accordion in Angular

I have the following HTML code snippet in my file: <div class="col-md-3 col-sm-2 col-2 collapsedData" > <a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="false" aria-con ...

The option buttons will be displayed when the ng-change directive is added to the ion-toggle element

Greetings! I am relatively new to Ionic and mobile development. I am currently working on a simple reminder app and integrating the ion-toggle feature into it. Below is an excerpt of my code: <ion-item class="item-avatar" ng-repeat="med in meds.medicat ...

Example of a floating undo bar using a dynamic function in a Vuex store module

Issue Overview Trigger the mutation or action of Vuex store module A to execute an external function. This external function can belong to another Vuex store module (e.g. B). A should store a reference to the external method (e.g. mutation or action from ...

The type 'string' does not share any properties with the type 'CSSProperties'

How can I resolve the issue of Type 'string' has no properties in common with type 'CSSProperties'? const points = 100; const radius = 257; const max = 100; const peaks = [ 10, 50, 90 ]; const step = ...

Angular - Ensuring correct rendering of a subcomponent with input parameter on the first update

Here is a snippet of code showcasing a list of educations and a component: <cdk-virtual-scroll-viewport itemSize="5" class="list-scroll"> <app-education-item *ngFor="let education of loadedEducations" ...

The element is implicitly assigned an 'any' type due to the fact that an expression of type 'any' cannot be used to index types in nodejs and solidity

I am in need of setting networks in my contract using NodeJS and TypeScript. Below is the code I have written: let networkId: any = await global.web3.eth.net.getId(); let tetherData = await Tether.networks[networkId]; Unfortunately, I encountered ...

Tips for adjusting card content to fit its size in material ui?

I'm looking to implement Material UI cards in a grid layout, each containing a Highcharts chart as shown in this demo. However, I'm facing an issue where the content does not adjust properly when the card size is fixed. How can I resolve this? A ...

Launching a web application on Vercel, the back-end has yet to be initialized

I am currently working on a Next.js/TypeScript web application project hosted on Vercel's free tier. To run my project, I use npm run dev in the app folder to start the front end and then navigate to the back-end folder in another terminal and run npm ...

Resizing a column in the Bootstrap CSS grid causes adjacent columns to move

I am currently working with a bootstrap grid that includes an expand component. The issue I am facing is that when I expand one column, the other columns in the same row also shift. Is there a way to make each column independent of the others? expand co ...

The Angular application is encountering difficulty accessing the Django Rest Framework API due to a CORS problem

Encountering a CORS problem while trying to access a Django Rest Framework REST API from an Angular 6 application. The API is hosted at http://localhost:55098/admin. It functions properly when accessed with Insomnia. The Angular app is running on http://l ...

Angular - issue with subject observable not functioning as expected

In my service SelectorService, I have created a subject and an observable. private eventEligibleApiStatus = new Subject<any>(); public eventEligibleApiStatusUpdated$ = this.eventEligibleApiStatus.asObservable(); I also have a method in which I use s ...

Sample test scenario for a service function that includes an HTTP subscription using Angular's HTTP RxJS

I have a service method that includes an HTTP call and subscribes immediately to the response code in order to execute the rest of the action command based on it. Here is an example of the service method: processData(id): void { const url = `http://l ...

What is the best approach to implement a recursive intersection while keeping refactoring in consideration?

I'm currently in the process of refactoring this code snippet to allow for the reuse of the same middleware logic on multiple pages in a type-safe manner. However, I am encountering difficulties when trying to write a typesafe recursive type that can ...