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

Unable to utilize SASS variables in Angular from a global file, even though other styles are functioning correctly

After implementing the SASS code in my component's style, it functions correctly. $test-color: pink; div{ background-color: $test-color; } However, when I transfer the definition to styles.scss, the desired outcome is not achieved. I have attempted u ...

Utilizing Angular 2 alongside ngrx/store for seamless updates to specific properties within the state object without disrupting the entire structure

I am facing an issue where I need to update a property of a state object without creating a new object. Is there a way to add or update a single property without replacing the entire object? Below is the reducer code: const initialState = { all: [], ...

An error was encountered while attempting to redirect in an Angular 4 project, the URL was set up for HTTPS

I've been attempting to access an Angular 4 project deployed locally on my machine through a form on an HTML page: <!DOCTYPE html> <html> <body> <form action="https://test-pubg.sohum.com:4200" target="_blank" method="post"> ...

Generating a dynamic clickable div using Angular 6

How can I create a user-friendly interface that displays an image with clickable divs around detected faces, allowing users to view specific attributes for each face? I'm looking for a solution where I can have divs or buttons around each face that t ...

Unable to activate parameter function until receiving "yes" confirmation from a confirmation service utilizing a Subject observable

Currently, I am working on unit tests for an Angular application using Jasmine and Karma. One of the unit tests involves opening a modal and removing an item from a tree node. Everything goes smoothly until the removeItem() function is called. This functi ...

Sending information from a component to a route in Angular2

Is it possible to transfer data from one component to another without displaying it in the URL during routing? Currently, I am passing data using route parameters like this: { path: 'edit-tags/:type/:name/:id', component: EditTagsCompon ...

What could be causing the conditional div to malfunction in Angular?

There are three conditional div elements on a page, each meant to be displayed based on specific conditions. <div *ngIf="isAvailable=='true'"> <form> <div class="form-group"> <label for ...

I require all of this to be brought back as one complete entity. If, for instance, the object is given the value 10/26, it should be interpreted as part of the input

I am facing an issue with my Angular + .NET Application where the search method is not recognizing a specific ConsumerUnit when the input includes a / character. Currently, if I input something like 10/2689123, the application treats the / as part of the ...

Display a free Admob banner within an Ionic 3 application

I have integrated Admob's banner into my Ionic 3 app following the guidelines provided in the Ionic documentation at this link. Below is the code snippet I used for displaying the banner on the homepage: import { Component } from '@angular/core ...

Encountering a 'No overload matches this call.' error when using ApexCharts with Typescript and ReactJS

As a newcomer to Typescript, I am gradually familiarizing myself with this powerful tool. After fetching the OHLCV data from coinpaprika and passing it to ApexCharts, I encountered an issue while trying to map the raw data: ERROR in src/routes/Chart.tsx:3 ...

When declaring an array of numbers in sequelize-typescript, it triggers a TypeScript error

In my application, I am working with PostgreSQL, Sequelize, Sequelize-TypeScript, and TypeScript. I have a need for a table called Role where each role has multiple permissions of type integer. I'm following the guidelines provided in the sequelize-ty ...

What steps should I take to instruct the browser to utilize a cache manifest if service workers are not supported?

How can I instruct the browser to utilize a cache manifest if it does not support service workers? I am working on an Angular 4 application that must be able to run offline. While service workers are effective for this purpose, they are unfortunately not ...

Can someone provide guidance on integrating UI components with Angular 8?

I have developed my own custom component called app-button.ts. This component is responsible for checking the current user's roles and rendering the button only if it matches the defined roles. The ButtonType property is used to specify the style of ...

The significance of Import and Export in the Initialization of Angular's NgModule

I recently completed the Angular Tour Of Heroes tutorial and reached the router section. I came across this code snippet in the app-routing.module.ts file that left me puzzled: app-routing.module.ts file: @NgModule({ //Exporting the routermodule allo ...

Mapping an array based on specific conditions

When using my photo gallery app, I faced a challenge in mapping an array of images based on the user-selected album name. The current setup works perfectly for the 'Cambodia' album where all images are correctly logged in the console after mappin ...

The parameter 'unknown[]' cannot be assigned to the type 'OperatorFunction'

component.ts initialize() method explains The error message says 'Argument of type 'unknown[]' is not assignable to parameter of type 'OperatorFunction<unknown[], unknown>'. Type 'unknown[]' does not match the si ...

The file path and installed npm package intellisense does not appear in VS Code until I press Ctrl + space for TypeScript

Before pressing ctrl + space, intellisense shows: click here for image description After pressing ctrl + space, intellisense displays: click here for image description Upon updating to vs code version 1.11.0 and opening my project, I encountered an issu ...

Angular 4 animations failing to run on Safari iOS 9.3

In my current app testing phase, I noticed that the angular animations are not functioning as expected in Safari iOS 9.3. Despite spending hours trying to troubleshoot the issue, I still couldn't resolve it on my own. Therefore, I am seeking assistanc ...

React textarea trigger function on blur event

https://codesandbox.io/s/react-textarea-callback-on-blur-yoh8n?file=/src/App.tsx When working with a textarea in React, I have two main objectives: To remove focus and reset certain states when the user presses "Escape" To trigger a callback function (sa ...

There was an issue converting the value {null} to the data type 'System.Int32', resulting in a 400 error

Attempting to make a POST request with some missing data is causing errors in my angular form. Here is the payload I am using: DeviceDetail{ deviceId:'332', sideId: null, deviceName:'test' } Unfortunately, I encountered a 400 bad re ...