Tips for handling numerous buttons in ionic?

I'm currently working on an app that includes surveys. In this app, users are required to answer by selecting either the Yes or No button. The desired behavior is for the chosen button to turn blue once clicked, while the other button should maintain its default appearance. However, I encountered a problem where clicking one button also changes the color of the other buttons to blue, instead of just the selected one. I attempted to implement a solution from this resource, but it did not resolve the issue as all buttons still turned blue upon click. As a beginner in learning Ionic, any assistance would be greatly appreciated.

The following image shows the default appearance of the button:

https://i.stack.imgur.com/No1Rj.png

After a user taps an answer, only that specific button should have a blue background. Unfortunately, when a button is tapped, both buttons end up turning blue.

https://i.stack.imgur.com/cYdjp.png

Below are the code snippets:

.html

<ion-row>
    <ion-col size-md = "6">
      <ion-button id = "q1-yes-on" [ngClass]= "isClicked('q1-yes-on') ? 'btn-pressed' : 'btn-unpressed'" id = "q1-yes-off" (click) = "onClick('q1-yes-off')" fill = "clear">
        <div class = "parentElement">
          <img src = "{{myYesImage|staticpath}}"/>
          <br><br><p class = "btn-work"><b>Yes</b></p>
        </div>
      </ion-button> 
    </ion-col>
    <ion-col> 
      <ion-button id = "q2-yes-on" [ngClass]= "isClicked('q2-yes-on') ? 'btn-pressed' : 'btn-unpressed'" id= "q2-yes-off" (click) = "onClick('q2-yes-off')" fill = "clear">
        <div class = "parentElement">
          <img  src = "{{myNoImage|staticpath}}"/>
          <br><br><p class = "btn-work"><b>No</b></p>
        </div>
      </ion-button>
    </ion-col>
  </ion-row>

.ts

     isClick: boolean = false;

     private _id: string;

       isClicked(_id){
           console.log(_id);
           return this.isClick

 
        } 

     onClick(_id){
              console.log(_id);
              this.isClick=!this.isClick;
      }

Answer №1

create a unique variable for each group of buttons. This variable can have three values, such as null, true, and false - or you can choose three other values like -1, 0, and 1, or 0, 1, and 2

<button (click)="variable=variable!==true?true:null"
    [style.background-color]="variable===true?'blue':null">
     yes
</button>
<button (click)="variable=variable!==false?false:null"
    [style.background-color]="variable===false?'blue':null">
    false
</button>

Imagine you have a list of buttons, where each button represents a question. You can loop over an array of objects "questions", with each object having a property called "response". Consider an array of questions like

questions=[
           {text:"2+2 is equal 4",response:null},
           {text:"2+2 is equal 5",response:null}
            ...
]

In this case, simply replace the "variable" with "question.response" in the code from before:

<div *ngFor="let question of questions">
    {{question.text}}
    <button (click)="question.response=question.response!==true?true:null"
        [style.background-color]="question.response===true?'blue':null">
         yes
    </button>
    <button (click)="question.response=question.response!==false?false:null"
        [style.background-color]="question.response===false?'blue':null">
          false
    </button>
</div>

Make sure to declare the variables in your .ts file. Additionally, you can check the responses by using:

<pre>
{{questions|json}}
</pre>

Answer №2

If you are dealing with multiple questions and answers as described in your query, my recommendation would be to utilize Ionic radio groups. This way, you won't have to worry about managing the selection of multiple answers by the user. The Ionic radio group will automatically indicate which option has been chosen by adding an active class. You can then easily style the buttons using CSS based on the selected option.

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 could be causing appendChild to malfunction?

I'm having an issue trying to create three elements (parent and one child) where the third element, an <a> tag, is not appending to modalChild even though it's being created correctly. modal = document.createElem ...

Dividing Trapezoid Shapes, Cropping Background Images

I am attempting to design a website layout with trapezoid shapes similar to the attached image. Each section should have a background image that fills the background with cover or a similar effect. I successfully created the first section (dark blue) usin ...

Reactive form allows you to easily format dates

Currently, the date displayed is 1/4/2022. We need it to display in the format 01/04/2022. Can we achieve this formatting using reactive forms with the sample Model form provided below? Thank you. How can we format it when starting from transactionStartD ...

Utilizing CSS float with dynamic height

Is there a way to achieve height:auto; for a parent element even when child elements are using float:left; or float:right? Solution for the Parent Element: #parent { width:100px; height:auto; padding-bottom:10px; background:#0F0; ...

How about this: "Unveil the beauty of dynamically loaded

var request = new Request({ method: 'get', url: 'onlinestatusoutput.html.php', onComplete:function(response) { $('ajax-content').get('tween', {property: 'opacity', duration: 'long&apos ...

Utilizing a function argument within the :not() selector

I am currently working towards the objective of selecting all elements in my document except for those within a specific class. This is what I have come up with so far: var x = document.querySelectorAll(":not(.myParameter)"); My aim is to make 'myPa ...

Making a secure connection using AJAX and PHP to insert a new row into the database

Explaining this process might be a bit tricky, and I'm not sure if you all will be able to assist me, but I'll give it my best shot. Here's the sequence of steps I want the user to follow: User clicks on an image (either 'cowboys&apos ...

@page Css not displaying properly on the Mozilla Firefox browser

In order to fulfill my requirement, I need to ensure that there is a consistent 10cm margin on all pages when printing. Printing on my web page involves utilizing the window.print() function. However, due to the dynamic nature of the content, the number o ...

JavaScript Processing Multiple Input Values to Produce an Output

Hello, I am working on creating a stamp script that will allow users to enter their name and address into three fields. Later, these fields will be displayed in the stamp edition. Currently, I have set up 3 input fields where users can input their data. He ...

The use of URL embedded parameters in @angular/http

Currently, I am utilizing a backend system that accepts search query parameters in both the ?-notation and the url-embedded format. I understand that I can use tools like URLSearchParams/RequestOptionsArgs to send requests to . However, I am curious about ...

The text on the menu is not adjusting properly for small screens

Check out the jsFiddle link. The issue arises when the Result screen is set to the width of a mobile's screen. Instead of wrapping the text, it gets replaced by dots and cannot be scrolled to view the full content. Here is the code snippet: <a hr ...

Looking to adjust the API response to fit the necessary JSON format for an Angular project?

A modification is needed in the API response to align with the required JSON format provided below. The current responses and the desired format are detailed for reference. Assistance is appreciated. The current representation of individual's data ne ...

Exploring Angular 2's @Input and @Output Directives

I'm unsure about whether I should be using @Input and @Output. From my understanding, these decorators are typically used when you want to establish communication between a parent and child component. Can you confirm or correct me on this? I have 3 c ...

Fade effect on content in Bootstrap carousel

I am currently making some updates to the website mcelroymotors.com. One issue I have encountered while working on the homepage carousel is that the caption only pops up on the first slide, and does not appear on any of the subsequent slides. I would lik ...

What is the method for enclosing the Font Awesome addition symbol within a bordered box to create the appearance of a button?

Here is a sample HTML code: <div id="menu-icon"> <div><i class="fa fa-plus fa-lg"></i></div> </div> And this is the corresponding CSS: #menu-icon { height: 45px; width: 45px; background-color: #A3D8D4; ...

Text parsing with jQuery

Hello fellow developers. I am interested in creating a text parser using jQuery. My goal is to develop a function that can take a string as input and convert it accordingly. Imagine we have a div with the following HTML structure: <div class="item"> ...

What's preventing me from using the left click function on my published blog post?

This is my first time creating a blogger template and everything seems to be working correctly. However, I have encountered one problem. For some reason, I am unable to left click on my blog post. I have not installed any right/left click disabler and I&a ...

Sending data from Spark to my Angular8 projectLearn how to seamlessly transfer data from your

I am utilizing Spark 2.4.4 and Scala to retrieve data from my MySQL database, and now I am looking to showcase this data in my Angular8 project. Can anyone provide guidance on the process? I have been unable to locate any relevant documentation so far. ...

Unable to update a single object within an array using the spread operator

I am currently working on updating an object within an array and have encountered some issues. In my initial code, I successfully updated a specific property of the object inside the array like this: var equipment = this.equipments.find((e) => e.id === ...

Is there a way to dynamically update text using javascript on a daily basis?

I am currently developing a script to showcase different content and images every day. While I have successfully implemented the image loop to display a new picture daily, I need assistance in achieving the same functionality for the title. My aim is to c ...