Repositioning of array values occurs during toggle in Angular

I currently have an array containing 4 values that I can toggle (remove and add to the array).

selectedSections: any[] = ['one', 'two', 'three', 'four'];

Next, there is a button that when clicked, will show or hide each selected value.

<button (click)="toggleVal('one')">Toggle One</button>
<button (click)="toggleVal('two')">Toggle Two</button>
<button (click)="toggleVal('three')">Toggle Three</button>
<button (click)="toggleVal('four')">Toggle Four</button>

My challenge lies in ensuring that when a value is added back, it returns to its original position rather than being appended at the end. Currently, whenever a value is added, it gets placed at the end of the array. I am looking for a way to either specify the position where it should be added or maintain its current position.

Below is the function responsible for toggling the values:

toggleVal(val: any) {
    if (this.selectedSections.includes(val)) {
      let index = this.selectedSections.indexOf(val);
      this.selectedSections.splice(index, 1);
    } else {
      this.selectedSections.push(val);
    }
    this.howMany();
    this.filterData();
}

Any suggestions on how I can achieve this desired behavior?

Answer №1

<button (click)="toggleSwitch('red', 1)">Switch Red</button>
<button (click)="toggleSwitch('blue', 2)">Switch Blue</button>
<button (click)="toggleSwitch('green', 3)">Switch Green</button>
<button (click)="toggleSwitch('yellow', 4)">Switch Yellow</button>

toggleSwitch(color: any, num: number) {
if (this.activeColors.includes(color)) {
  let idx = this.activeColors.indexOf(color);
  this.activeColors.slice(idx, 1);
} else {
  this.activeColors.splice(num, 0, color);
}
this.countColors();
this.updatePalette();
}

Answer №2

To pass a specific index value to your function in the HTML, you can incorporate the following code snippet: arr.splice(index, 0, item);

This line of code will effectively insert the specified 'item' into the 'arr' array at the indicated index position (without deleting any existing items).

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

Having trouble accessing the boolean value of a webComponent Stenciljs input checkbox within an Angular Reactive form

When using my stenciljs input checkbox component in Angular inside a reactive form, I encounter an issue where the value received is inverted and stored as a string rather than a boolean. The console.log output seems correct, but the form group value is ...

Having trouble with the JSON format within the 'operations' field in the formData of your Next.js application?

I encountered a mutation that looks like this- mutation signUp($avatar: Upload!) { signUp( avatar: $avatar input: { name: "Siam Ahnaf" email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail= ...

Calculator built with HTML, CSS, and JavaScript

Hi there, I'm experiencing some issues with my calculator. The buttons seem to be working fine and lining up correctly, but for some reason, nothing is showing up on the monitor or getting calculated when I press the buttons. Here's the code that ...

Change the color of the plotly button when it is clicked

I recently implemented a custom button on my plotly modeBar and I would like it to retain a distinct color when clicked. This would help visually indicate its "active" state, allowing users to easily discern whether it is enabled or disabled based on its ...

Angular 10 reports that the Cookies and Local Storage are devoid of any data when running on localhost:4200

Why are Cookies and Local Storage not saving data when my Angular10/Express app is running on localhost? When I deploy the application to the server, Cookies and Local Storage work fine. However, when running the app on localhost (:4200 FE, :3000 BE), the ...

Unexpected request causes a dilemma during the karma test for an Angular directive

Let's discuss a straightforward directive: 'use strict'; angular .module('app') .directive('ngEmailMask', ngEmailMask); function ngEmailMask() { var directive = { replace: true, restrict: 'EA', ...

Converting changing inputs using Angular 5

I am working with a JSON translation file that contains translations for both English and German languages. Here is an example of the English translation file: en.json "COLORS": { "BLUE": "Blue", "RED": "Red", "GREEN": "Green" } ...

Utilizing React and MobX to dynamically render components based on observable arrays

I'm currently facing a challenge with trying to map an array in order to display components for each entry. Here's my current approach: Here is the structure of my RankStore; const RankStore = observable({ loading: false, error: "", ra ...

Build dynamic dropdown menus in Angular.js using cookie data

I'm facing an issue with populating a three-tier dependent dropdown in Angular with saved cookies. Sometimes, all three tiers populate correctly, but other times they show as blank strings or only partially populated. Upon inspecting the HTML code, I ...

HTML code that has been "commented out" means

Within my _Layout.cshtml file, the following lines are present: <!--[if IE 7]> <link rel="stylesheet" type="text/css" media="all" href="/Content/css/ie7.css" /> <![endif]--> <!--[if IE 6]> <link rel="stylesheet" type="te ...

Enhance jQuery event handling by adding a new event handler to an existing click event

I have a pre-defined click event that I need to add another handler to. Is it possible to append an additional event handler without modifying the existing code? Can I simply attach another event handler to the current click event? This is how the click ...

Sending Angular Material Select Option Value for Submission

HTML: <form id="reg" name="reg" enctype="application/x-www-form-urlencoded" action="http://api.phphotspot.com/v-2/client-register" method="post"> <md-input-container class="md-block"> <label for="country">Country</label&g ...

Sync user information when alterations are made on a different device

As I create a Discord clone using Next.js, I've encountered an issue where when a server is deleted, another client can still see and use the server until the page is reloaded. When testing out the official Discord web app, changes seemed to happen in ...

CSRF validation did not pass

I am currently working on a project in Django where I am trying to send an image file using XMLHttpRequest(). Below is the script I am using: $('#edit_user_image').change(function(){ var client = new XMLHttpRequest(); var file = document ...

Updating variable values using buttons in PHP and Javascript

I've implemented a like/unlike button along with a field displaying the number of likes. The code below uses PHP and HTML to echo the variable that represents the total number of likes: PHP-HTML: <span>likes: <?php echo $row['likes&apo ...

Optimal Strategy: Utilizing Spring Boot for Backend Development and jQuery for Frontend Interface

I am currently tackling a project that involves a Spring Boot 2 Backend and a jQuery Frontend. The frontend communicates with the backend by sending Ajax requests to Spring REST controllers in order to interact with database entities. One of the challenge ...

The implementation of classList.toggle in my JavaScript code is not functioning as expected

I created a button that toggles the visibility of a div. It works fine the first couple of times, but then it stops working. When I click on column1, the hidden div inside column1 doesn't appear. But when I click on column2, the hidden div inside colu ...

Using JavaScript to save coordinates as a 2D Vector Object

Which option is optimal for both memory usage and calculation speed? new Float32Array(2); new Float64Array(2); {x: 0, y: 0}; [0, 0]; It's clear that option 1 uses less memory than option 2, but what about speed? Are calculations faster with 32 bits ...

Leveraging Vue.js plugin within a single file component

I am looking to utilize the vue-chartkick plugin in my Vue application, but I want to register it within my single-file components instead of globally. Is there a way to achieve this same functionality without using Vue.use(VueChartkick, { Chartkick })? ...

Iterating through each loop and storing the values in an array

After researching various topics related to the issue, I found that the solutions provided are not working for me. It seems like there is a logic problem in my code. It's quite simple - I have two arrays (one containing three strings and the other con ...