Angular's ng-select fails to select the value when generating the dynamic control

Currently, I am working on dynamically adding cities using ng-select in order to have search functionality while entering city names. For example, if I have two city names saved in a form and need to display them in separate ng-select controls when editing - for instance, the first control should default to New York and the second to Texas.

<div *ngFor="let savedEntry of savedEntries; let i = index;">
  <ng-select [(ngModel)]="savedEntry.name" [id]="'city-id' + i" name="city">
    <ng-option value="">Select</ng-option>
    <ng-option *ngFor="let city of cities" [value]="city">
      {{ city}}
    </ng-option>
  </ng-select>
</div>

Sample data:

  public savedEntries: any[] = [
    { id: 1, name: 'Chicago' },
    { id: 2, name: 'New York' },
    { id: 3, name: 'Texas' }
  ];

  public cities: string[] = ['San Diego', 'New York', 'Texas', 'Ohio', 'Chicago', 'Houston', 'Phoenix'];

I am attempting to preselect default cities, but encountering an error stating that ng-option does not support options. Any suggestions on how to resolve this issue?

Answer №1

It seems like you are attempting to preselect the default value for your ng-select components based on the capitalCity values. However, the use of the [selected] attribute is not supported within ng-option elements. Instead, this can be achieved by utilizing the [compareWith] attribute provided by ng-select.

Here is a suggested modification to your code to achieve the desired functionality:

<div *ngFor="let capitalCity of capitalCities; let i = index;">
  <ng-select [(ngModel)]="capitalCity.name" [id]="'city-id' + i" name="city" [clearable]="false" [compareWith]="compareCities">
    <ng-option value="">Select</ng-option>
    <ng-option *ngFor="let city of cities" [value]="city.name">
      {{ city.name }}
    </ng-option>
  </ng-select>
</div>

Within your component class, define the compareCities function to specify how the comparison between the selected value and option values should be handled:

compareCities(city1: any, city2: any): boolean {
  return city1 && city2 ? city1 === city2 : city1 === city2;

In this particular example, the compareCities function compares the selected city name (capitalCity.name) with the available option values (city.name). If the comparison evaluates to true, the respective option will be preselected.

Remember that in the given scenario, capitalCity.name must exactly match one of the city names listed in the cities array. Otherwise, the Select option will be displayed as default.

Additionally, ensure that all required properties and structures such as capitalCities and cities are properly defined within your component class for this code to function correctly.

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

Incorporating TypeScript seamlessly into your current Create React App project without the need to modify any existing code or files

While I have already installed Typescript in my project, I am more concerned about adding new .tsx files and ensuring they are type-checked. Simply renaming existing .js files to .tsx is not a viable solution, as it requires refactoring all the existing ...

Is it possible to utilize an XML format for translation files instead of JSON in React Native?

I'm in the process of creating a react native application using the react i18next library. For translations, I've utilized XML format in android for native development. In react native, is it possible to use XML format for translation files inste ...

I am experiencing slow load times for my Angular 2 app when first-time users access it, and I am seeking assistance in optimizing its speed

Below, you'll find a snippet from my app.ts file. I'm currently working with angular2, firebase, and typescript. I'm curious if the sluggish performance is due to the abundance of routes and injected files? The application functions smoot ...

The specified type does not meet the constraint as it lacks the required index signature

I'm currently working on refactoring a TypeScript project that utilizes React Hooks. While I have some knowledge of TypeScript, I am still more of a beginner than an expert. My main goal is to create reusable code for this project through the use of ...

Showcasing diverse content with an Angular Dropdown Menu

I'm currently developing an angular application, and I've encountered a difficulty in displaying the user's selection from a dropdown menu. To elaborate, when a user selects a state like Texas, I want to show information such as the period, ...

Tips for emptying the search field in primeng multiselect widget

Is it possible to reset the search input field in primeng multiselect? I've been referring to the tutorial on primeng multiselect provided in the following article. https://www.primefaces.org/primeng/showcase/#/multiselect https://i.stack.imgur.com ...

Encountering an error when attempting to store a value in an array of custom types: "Unable to assign properties to undefined (setting 'id')"

My model looks like this: export class SelectedApplicationFeatures { id: number; } In my TypeScript file, I imported the model as shown below: import { SelectedApplicationFeatures } from "src/app/models/selectedApplicationFeatures.model"; selec ...

Angular: efficient exchange of information among components

I have a component X that handles a WebSocket. And within component X, I also have multiple presentation components (e.g. Y). Whenever the WebSocket receives a specific message, I need to perform an action in a particular component (e.g. refresh data). To ...

Guide to customizing the appearance of a component's host element on-the-fly

For instance: https://stackblitz.com/edit/angular-mkcfsd In my project, I have an icon component called app-icon which dynamically takes a path and inserts it into an SVG viewbox. I extract the height and width of the path, then set the SVG to match those ...

Error encountered with TypeScript template literals strings type

There's a new feature in the latest version of Typescript that allows the use of template literal strings as types, like this: type Hey = 'Hey'; type HeyThere = `${Hey} There`; It works perfectly in the Typescript playground with version 4 ...

Beware of the 'grid zero width' alert that may appear when utilizing ag-Grid's sizeColumnsToFit() function on multiple ag-Grids that are shown within a tab menu

Encountering a warning message when resizing ag-Grid and switching between tabs. The warning reads: ag-Grid: tried to call sizeColumnsToFit() but the grid is coming back with zero width, maybe the grid is not visible yet on the screen? A demo of this ...

Unexpected behavior with HashLocationStrategy

I am currently tackling a project in Angular2 using TypeScript, and I seem to be having trouble with the HashLocationStrategy. Despite following the instructions on how to override the LocationStrategy as laid out here, I can't seem to get it to work ...

"Improve your Angular ngrx workflow by utilizing the sandbox pattern to steer clear of

Currently, I'm trying to determine whether my implementation of the ngrx and sandbox pattern is effective. Here's the issue I'm facing: getFiles(userId: number, companyId: number) { this.fileService.getFiles(userId, companyId).subscribe(re ...

Enhance the angular 2 dependencies within the angular2-cli project

After experimenting with Angular 2 and following the guide on their website, I attempted to switch to Angular 2 CLI. However, the Angular 2 CLI project does not have the latest dependencies, resulting in errors from the compiler related to certain commands ...

Manipulating CSS Class Properties Using JavaScript

In my JavaScript application, there is a functionality that loads a list of items for users to click and view detailed information in a separate div on the page. Users should be able to interact with and make modifications to these individual item overview ...

What is the best way to utilize a component's property within a parent abstract class?

Custom Class: export abstract class CustomClass { constructor(); customMethod() { // accessing the name input of SomeComponent here; } } Some Component: export class AnotherComponent extends CustomClass { @Input() name: string; constru ...

The Next.js React framework seems to be having trouble reading user input from a

I'm encountering an issue when attempting to save form email/password registration using Next.js as it is throwing an error. import {useState} from 'react' type Props = { label: string placeholder?: string onChange: () => void na ...

Ensuring Data Consistency: Using TypeScript to Strongly Type Arrays with Mixed Variable Types

I have a JSON array that may contain objects of two types, defined by IPerson and ICompany. [ { "Name" : "Bob", "Age" : 50, "Address": "New Jersey"}, { "Name" : "AB ...

The AngularJS Service fails to properly convert incoming Json Responses into Model objects during piping

I have been studying AngularJS 17 and recently developed a login application. However, I am facing an issue where the server response is not being properly mapped to the object in the Model Class. Response: { "id": 1, "userName& ...

User Interface showcasing real-time progress data pulled from API

Currently, I am facing a situation where there are three docker containers involved in my project: - An angular frontend - A Django backend - A Python processing API The scenario is such that a user uploads a file to the backend volume through the fronten ...