Disabling the last control in a formGroup when sorting an array with Angular

I am facing an issue with sorting an array based on a numeric control value inside a formGroup nested in another array:

const toSort = [
  ['key2', FormGroup: {controls: {order: 2}}],
  ['key1', FormGroup: {controls: {order: 1}}]
  ]

The goal is to display the controls in the form in a specific order. I have successfully sorted the array, but after submitting the form, the last control is not updating with the new value. However, when the controls are automatically sorted alphabetically, all values update correctly.

This is the sorting function I used:

toSort.sort((val1, val2) => {
      return val1[1].controls.order.value - val2[1].controls.order.value;
    });

Any insights on why this behavior is happening?

Answer №1

After some troubleshooting, I finally cracked the code. The issue stemmed from my failure to reassign the sorted array to itself following the sorting process.

const toSort = [
  ['key2', FormGroup: {controls: {order: 2}}],
  ['key1', FormGroup: {controls: {order: 1}}]
  ]
  
 toSort = toSort.sort((val1, val2) => {
  return val1[1].controls.order.value - val2[1].controls.order.value;
});

Answer №2

make a modification

alter value by subtracting val1[1].controls.order from val2[1].controls.order
=>
val1[1].controls.order - val2[1].controls.order

https://docs.angularjs.org/api/ng/filter/orderBy

refer to orderBy filter for more information

Answer №3

Update your sorting algorithm and give it a go

Also, refer to ngForOf here

const toSort = [
  ['key2', {FormGroup: {controls: {order: 2}}}],
  ['key1', {FormGroup: {controls: {order: 1}}}]
  ]

toSort.sort((val1, val2) => {
  return val1[1].FormGroup.controls.order - val2[1].FormGroup.controls.order;
});

console.log(toSort);

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

Exploring objects as strings to retrieve data with Javascript

In a scenario where I receive an object of varying length that I do not control, I am required to extract specific data from it. The response I receive is in the form of a formatted string: { "questionId": 18196101, "externalQuestionId": "bcc38f7 ...

What are the steps to implement the `serialport` library in `deno`?

After tinkering with Deno to extract readings from an Arduino, I encountered a roadblock when it came to using the serialport library correctly. Here is what I attempted: According to a post, packages from pika.dev should work. However, when trying to use ...

Exploring the process of querying two tables simultaneously in MySQL using PHP

I currently have a search box in my PHP file that only searches from the "countries" table. However, I also have another table called "continent" and I would like the search box to retrieve results from both the "countries" and "continent" tables. Here is ...

The window fails to retain the scroll position when overflow is enabled

Whenever I click on a specific div, I use jQuery to dynamically apply overflow: hidden to the html and body. $(".mydiv").on("click", function() { $("html, body").css("overflow", "hidden"); }); However, this action causes the window to scroll to the to ...

When working with React JS and the react-select library, I am looking to automatically reset the options to their default value once

I am attempting to disable the select list after unchecking the checkbox and resetting the select value back to default, but currently it is retaining the last selected option. I am utilizing React-select for the select and options in this scenario. APP.j ...

What is the most effective way to extract information from a .txt file and showcase a random line of it using HTML?

As a newbie in HTML, my knowledge is limited to finding a solution in C#. I am attempting to extract each line from a .txt file so that I can randomly display them when a button is clicked. Instead of using a typical submit button, I plan to create a custo ...

The projection of state in NGRX Store.select is not accurately reflected

Every time I run the following code: valueToDisplay$ =store.select('model','sub-model') The value stored in valueToDisplay$ always corresponds to 'model'. Despite trying various approaches to properly project the state, it s ...

What could be the reason why the @media print selector is not showing the correct format when I try to print?

When I click the print button, the text is supposed to display in four columns in the print dialog, but it appears as paragraphs instead. This is my script code where there is a click event for the print button. When I click on it, the print dialog pop ...

Error: The type 'boolean | (() => void)' cannot be assigned to type 'MouseEventHandler<HTMLButtonElement> | undefined'

Playing audio in a NextJS app while writing code in TypeScript has been an interesting challenge. The onClick() function performs well in the development environment, triggered by npm run dev. <button onClick ={toggle}> {playing ? "Pause" : ...

Troubleshooting: Fixing the "@angular/core" module not found error in Visual Studio 2019

As I embark on my Asp.Net Core Project with Angular template, I encounter an issue with every import row that includes '@angular/...'; import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-bro ...

Combining Data in React Arrays

I have an array with different group types and I need to merge the results if the grouptype is the same. const locationss = [ { grouptype: "Name1", id: "1", servicetype: [ { name: "Morning", price: "5& ...

The console.log method is not functioning properly in the service

When developing my Angular application, I encountered an issue while creating a service. Here is the code snippet: @Injectable({ providedIn: 'root' }) export class PropertiesNameService { properties: string[] = []; constructor(p ...

Directing to index.html using ExpressJS

JS, I am working on an express app that has various routes defined. However, I am facing an issue where if the router does not match any route, it displays index.html instead of redirecting to a specific route like '/*' as I expected. I am unsu ...

Error: Tried to modify a property that is read-only while using the useRef() hook in React Native with Typescript

https://i.sstatic.net/jhhAN.pngI'm facing an issue while attempting to utilize a useRef hook for a scrollview and pan gesture handler to share a common ref. Upon initializing the useRef() hook and passing it to both components, I encounter an error th ...

Implementing defaultProps in conjunction with withStyles

Currently, I am in the process of developing a component using material-ui withStylers and defaultProps. However, I have encountered an issue where the props of the component are not being retrieved in the styles objects unless they are explicitly passed t ...

What causes interface to generate TS2345 error, while type does not?

In the code below: type FooType = { foo: string } function fooType(a: FooType & Partial<Record<string, string>>) { } function barType(a: FooType) { fooType(a) } interface FooInterface { foo: string } function fooInterface(a: FooInt ...

Tackling JavaScript: Exploring Ternary Short Circuit and If Short Circuit

I am attempting to optimize the code by using a ternary operator to quickly return false. My understanding was that using a ternary in this scenario would have the same outcome as the if statement below it, which is to instantly return false if the lengths ...

"Encountering a hang while using the .save() function and only

Issue with storing data in MongoDB This is only my second attempt at saving data to a database and I am still relatively new to the process. I have a form on my HTML page that sends string data to be saved in a MongoDB database. I successfully connected t ...

Encountering a 404 error while attempting to utilize ng2-charts

I am encountering an issue while attempting to integrate ng2-charts. Despite going through numerous similar threads on GitHub and other platforms, I have yet to find a solution. The error message I am receiving is as follows: Error: (SystemJS) XHR error ( ...

Error: karma cannot locate the templateUrl for Angular component

I'm encountering some issues while running tests on angular directives with karma. The problem arises when the directive comes from a templateUrl and is not being translated properly. Here's my karma.conf.js configuration: 'use strict&apos ...