The sorting feature in Angular 4 appears to be dysfunctional

I encountered an error message that reads: "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type."

After reviewing the MDN explanation, I am still struggling to identify where the problem lies. When I remove the month from this.Months.push, the sorting works fine, but only numbers are displayed in the dropdown menu instead of the text representing the months.

Below is my code snippet:

<app-dropdown [ngModel]="selectedMonths" [multiSelect]="true" label="Select Month" labelWidth="75px"
optionWidth="150px" [items]="Months" (ngModelChage)="monthChange($event)">
      </app-dropdown>

This is the TypeScript code snippet:

purchaser: Map<string, Purchased>;

months: number [] = [];
Months: DropdownOption[] = [];

const monate = [
        'January',
       'February',
        'March',
        'Aprill',
         'Mai',
        'June',
        'July',
        'August',
        'September',
        'October',
        'November',
        'December'
];

this.purchaser.forEach(purchaserId => {
    if (!this.months.includes(purchaserId.created.getMonth())) {
        this.months.push(purchaserId.created.getMonth());
        this.Months.push({key: purchaserId.created.getFullYear().toString(), value: month[purchaserId.created.getMonth().toString()]});
    }
});

this.Months.sort((a, b) => +a.value - +b.value);
this.months.sort((a, b) => a - b);
month.sort((a, b) => a - b); // The error occurs at this line

Answer №1

@UniquAX. The issue is crystal clear,

//You have the option to
a=+"23" //a=23

//However
a=+"potatoe"  //Will result in an error

If you wish to arrange the months alphabetically by name you can use

this.monate.sort((a,b)=>{
     return a==b?0:a>b?1:-1;
})

It does seem odd though that you want to sort "some" with month based on the month's name :(

When utilizing something like "month", The key point is that "month" needs to be a number. If you want to display the month name you can, for example:

//Let's say your items are like [{data:"A",month:1}{data:"B",month:10}...]
//and you have defined in your .ts monate=['January','February'......] 

<div *ngFor="let item of items">
    {{item.data}}{{monate[item.month-1]}}
</div>

Alternatively,

//you could have an object item like {data:'A',month:3} and a form like

<form>
   <input [(ngModel)]="item.data"/>
   <select [(ngModel)]="item.month">
        <option *ngFor="let month of monate;let i=index" [value]="{{i+1}}"> 
             {{month}}
        </option>
   </select>
</form>

There is a distinction between the "data" and how the data is displayed

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

I'm experiencing difficulties with updating my model while utilizing the ngResource module

Encountering a minor issue with Angular at the moment. Employing the $ngResource module to fetch "comments" from my server: var app = angular.module('app', ['ngResource']); app.factory('comment', function($resource) { r ...

Controlling Fabric in Three.JS

(I'm still learning so forgive me if this is a beginner question.) I'm currently working on fitting a cloth material to a character model in Three.JS. What would be the most effective approach for this? Should I create a complete garment as cloth ...

AngularJS implementation that disables a button when the input field is empty

As I delve into learning angular JS, I am facing a challenge. I want to disable the button using the "ng-disabled" attribute while my input fields for "login" and "password" are empty. However, the default text in the login input is "LOGIN" and in the pass ...

Instantiate a TypeScript object and establish its type by setting restrictions derived from an input object

I have been working on creating a function that takes an object A: { [key: string]: string | undefined } as its parameter. The goal is to generate a new object B with all properties from A, converting each string property to type number, and each string | ...

Tips for automatically expanding all nodes with children when the page loads in the Wix Angular tree control

Is there a way to automatically expand all nodes with children when the page loads in an Angular tree control? The tree control is full of useful features, but this specific functionality seems to be missing. It does have a property for expanded nodes. Do ...

Angular 2 fails to redirect to a 404 page if both the route parameter and address are not valid

Currently, while working on my application with Angular 4.1.1, I have a habit of declaring routing in every module I create. For instance, in the file new-cars.routing.module.ts: import { NgModule } from '@angular/core'; import { RouterModule, ...

Making a call to Ajax while specifying the contentType as 'application/json'

After some troubleshooting, I discovered that removing the content-Type works fine. However, the jsonitem received on the PHP side is showing syntax errors. From my research, it seems like specifying the content type when sending Json objects is crucial. ...

Connecting extra parameters to an event listener

Scenario: I am facing a situation where my event handler is already receiving one parameter (an error object). However, I now need to pass an additional parameter when binding the event handler. I am aware of the bind() method, but I am concerned that it ...

CAUTION: Attempted to load angular multiple times while loading the page

I encountered a warning message while working on my project, causing errors in calling backend APIs due to duplicate calls. Despite attempting previously suggested solutions from the forum, I am stuck and seeking assistance. Can anyone provide guidance? Be ...

Typescript's tree-pruning strategy design for optimization

I've been working on developing a library that enforces the use of specific strategies for each target. The current structure I have in place is as follows: [Application] -> contains -> [player] -> contains -> [renderer] In the current s ...

Tips for showing a success notification once a PHP script has been successfully completed on a form

Hey everyone, I need some help with a PHP script that I have connected to a single input form. I'm looking to create a success page for users after they submit their email, with a link back. This seems simple enough, but I'm still learning PHP. ...

Sending data from a partial view to a controller

Imagine I have two models: DailyTasks and Task. The initial view is strongly typed with the DailyTasks model, displaying a list of existing tasks for the day. Users can add more tasks to the list/table by clicking the add button. Upon clicking the add butt ...

Unable to associate with 'userID' as it is not a recognizable attribute of 'view-user'

When looking at my template expression, I came across the following: This points to the ViewUserComponent, which includes: @Input() userID; I'm puzzled as to why I'm encountering this error: Can't bind to 'userID' since it isn& ...

Encountering issues with Windows 8 PhoneGap FileTransfer when trying to transfer text files

I'm facing an issue while attempting to upload a file to a server - the process seems successful, but the file doesn't actually transfer. I've temporarily hard-coded some values, but here's the code snippet: var options = new FileUplo ...

changing session variables in JavaScript

My index.php page contains all my PHP functions, JavaScript code, and HTML tags. I am trying to figure out how to call a PHP function (addToCart($itemID)) to update session variables when the user clicks on a button (add to cart). Can you provide guidanc ...

Difficulty arising from implementing v-if as a filter within a v-for loop in Vue.js

I'm struggling a bit with setting up a conditional statement using v-if along with a loop using v-for in Vue. Here's what I have so far: <div class="row form-group" v-for="(article, key, index) in articles" :key="key" v-if="article.pubdate(fi ...

Styling Angular 5 components without scoped styles

Currently, I am facing a dilemma with my Angular component that embeds a Microsoft PowerBI Report. The powerbi-client utilizes the nativeElement from an ElementRef to inject an iframe containing the report. My goal is to customize the styling of the border ...

Is it advisable to incorporate await within Promise.all?

Currently, I am developing express middleware to conduct two asynchronous calls to the database in order to verify whether a username or email is already being used. The functions return promises without a catch block as I aim to keep the database logic se ...

React | Utilizing ForwardedRefs with React Components

I'm currently working on a React project where I am creating a custom component that needs to be exported using forwardedRef. However, as I attempt to do this, an error keeps popping up: error This is the code snippet causing the issue: export inter ...

Filtering Date Ranges in Ant Design Tables

I have been attempting to add a date range filter to my Ant Design table by using the code provided here, but unfortunately, I have not had any success with it yet. It seems like it may not be compatible with the latest versions of Ant Design. Has anyone ...