Improve the way you manage the active selection of a button

ts

isDayClicked: { [key: number]: boolean } = {};


  constructor() { }

  setSelectedDay(day: string, index: number): void {

    switch (index) {
      case 0:
        this.isDayClicked[0] = true;
        this.isDayClicked[1] = false;
        this.isDayClicked[2] = false;
        break;
      case 1:
        this.isDayClicked[0] = false;
        this.isDayClicked[1] = true;
        this.isDayClicked[2] = false;
        break;
      case 2:
        this.isDayClicked[0] = false;
        this.isDayClicked[1] = false;
        this.isDayClicked[2] = true;
        break;
      default:
    }
  }

html

<ion-col size="4" *ngFor="let d of validDays;let i = index;">
      <ion-button expand="block" fill="outline" 
        [ngClass]="{'active':isDayClicked[i]}" (click)="setSelectedDay(d,i)">
        {{d}}
      </ion-button>
    </ion-col>

css

.active {
    background-color: var(--ion-color-primary);
}

UI

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

I have a set of buttons displayed above. To indicate an active button, I am currently using a hardcoded method to toggle between the buttons based on the click. Is there a more efficient way to achieve this functionality?

Note: While the current approach is functional, I am looking for optimizations or alternative methods to handle this scenario better.

Answer №1

If you want to achieve this, follow these steps:

Start by creating a new variable in your TypeScript file

public selectedDayIndex = null;

In your setSelectedDay function, update this variable accordingly.

setSelectedDay(day: string, index: number): void {
  this.selectedDayIndex = index;
}

Next, modify your HTML as shown below:

<ion-col size="4" *ngFor="let d of validDays; let i = index;">
  <ion-button expand="block" fill="outline" 
    [ngClass]="{'active': selectedDayIndex === i}" (click)="setSelectedDay(d, i)">
    {{ d }}
  </ion-button>
</ion-col>

If you encounter any issues or have questions, feel free to ask for further clarification.

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

Improve the Popup to seamlessly elevate

In my project, I have implemented a pop-up dialog box that rises up from the left bottom corner as the user scrolls down the page. You can view it live at this link- However, I am facing an issue where the initial lift up of the dialog box is not smooth, ...

How can you display Bokeh HTML visualizations on your WordPress site?

I've developed a Python Bokeh dashboard with visualizations and saved the HTML file. Viewing it in my browser displays the graphs as expected. However, I'm facing issues trying to showcase this dashboard on my WordPress site. Simply pasting the H ...

Modifying the color of a div based on a specified value using JavaScript

<div id="navigation"> Add your text here </div> <input type="text" id="newColor"><button onclick="modifyColor()">Update</button> <script> function modifyColor(){ var chosenColor = document.getElementB ...

Issue: Unable to find Store provider while using @ngrx/store in Angular 4.0

Issue: Error: No provider for Store! I am trying to initialize the store module in main.ts: platformBrowserDynamic().bootstrapModule(AppModule,[ provideStore({ characters, vehicles }) ]); Then I am injecting it into vehicle.component.ts: c ...

Tips for quietly printing a PDF document in reactjs?

const pdfURL = "anotherurl.com/document.pdf"; const handleDirectPrint = (e: React.FormEvent) => { e.preventDefault(); const newWin: Window | null = window.open(pdfURL); if (newWin) { newWin.onload = () => ...

Bug with the button and text input feature in Firefox

I am facing a strange issue where the button and input have the same CSS (except for the background), but Firefox is displaying them differently. This problem does not occur in IE or Chrome. #searchInput { width: 80%; margin: 0 auto; display: ...

Trigger an event when an Angular template's *ngIf condition is met

Let's say I am using the Angular directive *ngIf to display a user object like so: <div *ngIf="user$ | async as user" class="container"> <p>{{user.name}}</p> </div> Is there a method where I can trigger some code once this ...

Issue: NG04002 encountered post migration from Angular to Angular Universal

Having recently created a new Angular app and converted it to Angular Universal, I encountered an issue when running the project using npm run dev:ssr. The error displayed in the terminal is as follows: ERROR Error: Uncaught (in promise): Error: NG04002 Er ...

Tips for integrating CSS with Material UI TableContainer

I have utilized Material UI Grid to display data in a chart. However, the appearance of the chart does not match my expectations. Instead of resembling the desired "dense table," it looks different: Actual Look of the Chart Below is the code snippet I ha ...

What causes a delay in HTTP calls in Chrome when it is in the "Stalled" or "Initial Connection" state? Is it possible for these states to generate multiple threads for the same request?

My application uses Angular on the client side and Java (Spring Boot) on the backend. Occasionally, during some network calls, the waterfall chart gets stuck in either the "Stalled" or "Initial Connection" state. When this happens, I have noticed in my log ...

"Implementing a form submission feature in React.js that dynamically applies a class to the result element

I recently developed a basic BMI calculator using React.js. I am now attempting to implement a feature where if the calculated BMI result falls outside the range of a healthy BMI, the result text will be displayed in red color (I am utilizing styled-compon ...

The JavaScript code appears to be missing or failing to execute on the website

Encountering a console error while trying to integrate jQuery into my website. The JavaScript file is throwing an error in the console that says: Uncaught ReferenceError: $ is not defined catergory.js:1 Even after following the suggested steps in this an ...

What is the best method for displaying a view on a new page in Angular 2?

Currently, I am facing a challenge with my Angular 2 project. I am struggling to figure out how to make a route open a new view instead of simply rendering in the same page. My goal is for the route to lead to a completely separate view rather than stayi ...

Is there a way to extract a list of words from a designated element using selenium?

I have been trying to scrape the content of this webpage 10 Fast Fingers in order to extract the words that need to be typed into a list. My intention is to then input these words into a text box for typing practice. The code seems to be running fine, but ...

Combining keyframe properties in a more efficient way using less code

While attempting to develop a LESS mixin for CSS3 keyframes, I encountered the typical way of chaining IDs and classes: #idOne, #idTwo, .classOne, .classTwo { ... } Nothing groundbreaking there. What I'm currently working on is crafting the foll ...

What could be preventing my state from changing to false when I click the close button on the menu?

Despite initializing my state to false, the problem arises when I open and close my menu. The state never actually becomes false, causing the closing animation of the NavBar to not run as expected. The component: import CloseButton from "./CloseButto ...

What is the process for transforming a string literal type into the keys of a different type?

Imagine having a string literal type like this: type Letters = "a" | "b" | "c" | "d" | "e"; Is there a way to create the following type based on Letters? type LetterFlags = {a: boolean, b: boolean, c: bool ...

Support for Arabic in database, PHP, and JavaScript

After inputting an Arabic comment into a textarea on the site, it displays correctly as "عربي" and is successfully sent to the database. However, upon refreshing the page, the text appears garbled: "عربÙ�". I attempted to directly enter s ...

Table that can be scrolled through

Back in 2005, Stu Nichols shared a technique for creating a fixed header with scrolling rows in a table on this site. I'm curious if there are any newer methods or improvements to achieve the same effect, or is Stu's approach from 2005 still con ...

Pointer-enhanced Material UI Popup

Is there a way to implement a Popup that looks like the image provided using @Material-ui? https://material-ui.com/ I attempted to use Popover, however Popper does not include a pointer like in the image. https://i.stack.imgur.com/atz0G.png ...