Is the ng-selector in Angular2 not sorting items alphabetically as expected?

This code snippet demonstrates the use of ng-selector in an .html file

<ng-selector 
                name="company"
               [(ngModel)]="company_selected"

                [formControl]="loanApplyForm.controls['company']"
                (loadValues)="fetchHLCompany($event)"
                id-field="id" label-field="name"
                 [options]="company_values"
                 allow-creation="true"
                 placeholder="Search your company">
</ng-selector>

I am facing a couple of issues with this implementation. When I enter a value, it prompts to add even if the typed value is already in the list. I want it to only ask to add if the input value is not in the existing list. I tried removing 'allow-creation' but then it doesn't prompt at all. Secondly, the search functionality is not sorting results alphabetically. Any assistance on these matters would be greatly appreciated. Thank you in advance.

Answer №1

If I understand correctly, you can achieve the following:

<ng-selector 
                name="company"
                [(ngModel)]="company_selected"

                [formControl]="loanApplyForm.controls['company']"
                (loadValues)="fetchHLCompany($event)"
                id-field="id" label-field="name"
                [options]="company_values"
                allow-creation="checkAddNewItem()"
                placeholder="Search your company">
</ng-selector>

Here is the function being used:

checkAddNewItem() {
   return !company_values.filter(item => item.includes(company_selected)).length;
}

This function checks if any values in the array contain the inputted values. If any do, it returns true and allows for the addition of that value.

In response to a follow-up question about sorting the options list, you need to sort it before setting it in the component upon retrieval.

company_values.sort((a, b) => a.localeCompare(b));

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 with NPM build getting stuck in Azure DevOps

There seems to be a problem similar to the one discussed in this question: npm run build hangs indefinitely on azure. Our build process has been functioning smoothly for several months. However, we are currently facing an issue where npm build is failing ...

The data remains undefined even after being initialized in the constructor

My goal is to extract queryParams from a URL and leverage that information to resolve data in the following manner: data = { searchValue: null || undefined }; constructor(private http: HttpClient, private route: ActivatedRoute) { route.queryParams.su ...

Implementing method overrides in TypeScript class objects inherited from JavaScript function-based classes

I am facing a challenge with overriding an object method defined in a JavaScript (ES5) function-based class: var JSClass = function() { this.start = function() { console.log('JSClass.start()'); } } When I call the start() method, it pri ...

Unraveling the Mystery: How Angular Handles Propagation of Color CSS Property Settings to Nested Components

Angular's style scope and inheritance are detailed in the guide: The styles defined in @Component metadata only affect the template of that specific component. They do not get passed down to any nested components or projected content. To propagate ...

Can one validate a single route parameter on its own?

Imagine a scenario where the route is structured as follows: companies/{companyId}/departments/{departmentId}/employees How can we validate each of the resource ids (companyId, departmentId) separately? I attempted the following approach, but unfortunate ...

Discovering subtype relationships in JSON with TypeScript

Consider the scenario where there are parent and child typescript objects: class Parent { private parentField: string; } class Child extends Parent { private childField: string; } Suppose you receive a list of JSON objects for both types via a R ...

Ways to speed up the initial loading time in Angular 7 while utilizing custom font files

Storing the local font file in the assets/fonts folder, I have utilized 3 different types of fonts (lato, raleway, glyphicons-regular). https://i.stack.imgur.com/1jsJq.png Within my index.html under the "head" tag, I have included the following: <lin ...

Dependencies for Angular2 Material components on npm

I currently have the following dependencies listed in my package.json for npm to locate and install. "@angular/material": "2.0.0-beta.1" "angular-material": "^1.1.1" If I want to utilize the most up-to-date versions, what exactly should I specify? I am s ...

"Encountering issues with ngrx store selector when importing app from a custom

My Angular library includes a store implementation and is distributed as an NPM package, used in various Angular applications. I encountered an error when attempting to use a ngrx store selector exported from the library in a different Angular project: ...

Tips for incorporating confidence intervals into a line graph using (React) ApexCharts

How can I utilize React-ApexCharts to produce a mean line with a shaded region to visually represent the uncertainty of an estimate, such as quantiles or confidence intervals? I am looking to achieve a result similar to: ...

Understanding the data types of functions in TypeScript can be quite important for

What type of information is required after the colon : in this specific function? public saveHistory(log: String): "HERE!" { return async (req: Request, res: Response, next: NextFunction): Promise<Response | void> => { try { ...

Troubleshooting npm test failure on CircleCI due to inability to locate installed package

It's puzzling that Circle is encountering issues with utilizing ts-mocha after it was successfully installed with npm install in a previous step of the build process. The functionality used to function properly, but now it suddenly stopped working. ...

ValueError: The object is not a valid HTMLInputElement in Angular 5

I'm attempting to implement autocomplete functionality for an address using the Google Maps API in my application, but I keep encountering the "InvalidValueError: not an instance of HTMLInputElement" error. Here are the approaches I have experimented ...

Using Angular 4 with Firebase to display nested objects within an object

My Firebase data: { "hotel" : { "-Kjgyamcup6ULm0Awa-1" : { "complete" : "true", "images" : { "-Kjgyb6A2gRiDhwaWx-V" : { "name" : "2.jpg", "url" : "https://firebasestorage.googleapi ...

React Router Issue: Component Not Rendering When <nav> Element Is Incomplete

I am currently experiencing an issue with rendering a component in my React TypeScript application using React Router. The problem arises when trying to navigate to the AddTask component by clicking on a link within a <nav> element. Strangely, the co ...

Typescript's Patch<T> type enforces strictness within the codebase

There have been instances where I needed to 'patch' an object T using Object.assign(). For instance, when propagating changes you might modify a stateful object that other code references (common in reactive programming like MobX or Vue). It&ap ...

Presentation of information with loading and error scenarios

How can we effectively display data in an Angular view, considering loading state and error handling? Imagine we are fetching a set of documents from our backend and need to present them in an Angular view. We want to address three possible scenarios by p ...

Exploring the depths of Rx.ReplaySubject: Techniques for delaying the `next()` event

Confused Mind: Either I'm mistaken, or the whiskey is starting to take effect. (I can't rule out the possibility that I'm just going crazy. Apologies for that.) Assumption: My assumption was that ReplaySubject would emit a single value eve ...

What is the correct way to utilize refetchOnReconnect for a builder.mutation endpoint in @redux/toolkit/query?

I'm having an issue with the Redux refetchOnReconnect option not working even after I have called the setupListener(store.dispatch) in my redux store.tsx file and set refetchOnReconnect=true to the endpoint hook call. store.tsx file 'use client& ...

How come the variable `T` has been assigned two distinct types?

Consider the following code snippet: function test<T extends unknown[]>(source: [...T], b: T) { return b; } const arg = [1, 'hello', { a: 1 }] const res = test(arg, []) const res1 = test([1, 'hello', { a: 1 }], []) The variabl ...