Tips for setting or patching multiple values in an ngselect within a reactive form

https://i.sstatic.net/ct6oJ.png I am facing an issue with my ng select feature that allows users to select multiple languages. However, upon binding multiple selected values in the ng select, empty tags are being displayed. I have included my code below. **When editing, I want to display the saved language tags on the ng select, but it is currently showing empty tags. Any assistance would be greatly appreciated. I am using a reactive form**

HTML

 <ng-select class="w-100" [multiple]="true"   [hideSelected]="true" placeholder="Please Select Language"
            formControlName="language" [bindValue]="language.id"  [bindLabel]="language.name" 
            >
            <ng-option *ngFor="let language of languages" [value]="language.id">{{language.name}}</ng-option>
          </ng-select>

Typescript

this.form.patchValue({ language: this.editData.teacherProfile.teacherProfile.language })

Data is retrieving in this form "language": [ { "_id": "5fb79cdd34ec021e64c2413e", "name": "English", "id": "5fb79cdd34ec021e64c2413e" }, { "_id": "5fb7996034ec021e64c2412a", "name": "Arabic", "id": "5fb7996034ec021e64c2412a" } ],

Answer №1

Ensure that the value you are assigning to the field is included in the available options

For example, if the select dropdown options include ids like 2, 3, 4, make sure to assign one of these values so that it will be displayed correctly

In this scenario, when sharing data with a specific structure, gather all ids into an array

languageID = [2, 3, 4, 5]

and then apply this array directly to the field using patchValue method

this.form.patchValue({ languageid: this.languageID })

Answer №2

ng-select receives input from an array, specifically an array consisting of IDs rather than objects.

To address this, you can write code like:

myForm.get('language').setValue(
               language.map(x=>x.id)
)

This example demonstrates how to extract a specific property, 'id', using the map method to create a new array.

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

Integration of Mocha with WebStorm

WebStorm offers a useful feature that adds a small arrow next to describe() and it() keywords when writing tests with Mocha, allowing for easy manual execution. However, there is a challenge: I require additional setup before each test, leading me to use ...

Error message is not shown by React Material UI OutlinedInput

Using React and material UI to show an outlined input. I can successfully display an error by setting the error prop to true, but I encountered a problem when trying to include a message using the helperText prop: <OutlinedInput margin="dense&quo ...

Having trouble importing the UpgradeModule from @angularupgradestatic in Angular version 2.2.1

I am in the process of updating my AngularJS (ng1) application to Angular 2 (ng2). My Angular version is 2.2.1. Upon importing UpgradeModule from @angular\upgrade\static, I encountered the following exceptions: Uncaught SyntaxError: Unexpected ...

Utilizing lodash and Angular 8: Identifying an valid array index then verifying with an if statement

In my current project, I am developing an e-commerce angular application that includes a basket with two types of products: restaurant + show combos and gift cards. When a client reserves a restaurant, they must also reserve a show; conversely, the client ...

Is TypeScript necessary, or can I simply stick with ES6?

As a client developer using AngularJS in my daily job, we are considering transitioning to TypeScript. After researching TypeScript, I discovered that most JavaScript packages I require need definition type files. This can be inconvenient, especially whe ...

Unable to find custom components when using react-router

My goal is to improve the organization of my Routes in React and separate concerns. I am currently utilizing react-router-dom version 5. Within my Application Routes component, I have structured it with 3 children components: AuthenticatedRoutes PublicRo ...

Slice an interactive div

I am currently working on setting up a horizontal sliding div for a menu. The layout consists of a left DIV that remains visible at all times, and a sliding DIV that appears horizontally when the menu is activated. My HTML code looks like this. <div id ...

Testing Slack's Web API with Jest for mock purposes

Currently, I am working with two files. One file is where I set up a slack web API client to post a message and test it with a mocked value: main.ts: import { WebClient } from '@slack/web-api'; const slack = new WebClient(process.env.SLACK_API_K ...

Issues arise when using Android BluetoothLeAdvertiser in Nativescript applications

I've been working on creating a Nativescript application that can send Bluetooth low energy advertisements. Since there are no existing Nativescript plugins for this functionality, I decided to develop a Java library (with plans to add a Swift library ...

Tips for setting up communication between UI and backend applications using Nginx reverse proxy in a Docker environment

We have an Angular UI application and a Java Spring Boot backend application. Our goal is to deploy them in Docker containers and establish seamless communication between the front-end and back-end without hard-coding URLs or other specifics. Everything ne ...

Preserving selected items in ag-grid when refreshing data sources

Just to clarify, this code snippet pertains to Angular 7 Interestingly, there is not much information available on this specific issue. I have a solution that is "working," but there is a minor issue with it. Essentially, I am calling an endpoint at regul ...

How can I access the component name and parameters during the NavigationEnd event?

We are currently setting up Google Analytics and we want to track the URL, parameters, and components in GA. this.router.events .pipe( filter(event => event instanceof NavigationEnd) ) .subscribe((event: NavigationEnd) => ...

Tips for working with Typescript: utilizing the default value for a non-existent computed property

When utilizing Computed Property in javascript, I can structure my code as follows const default_values = {a:"debug",b:"info",c:"warning"}; function execute(y) { let x = default_values[y] || default_values.a /* if y is no ...

What is the best way to mock imports in NestJS testing?

I am interested in writing a unit test for my nestjs 'Course' repository service, which has dependencies on Mongoose Model and Redis. courses.repository.ts: import { Injectable, HttpException, NotFoundException } from "@nestjs/common"; ...

Definition file in TypeScript for an npm package provided by an external source - constructor

In my Node project, I am utilizing ES6 and Typescript. Despite this, there is a commonjs library that I need to incorporate. To address this, I have created my own .d.ts declaration file for the library: module "@alpacahq/alpaca-trade-api" { e ...

How to update an Array<Object> State in ReactJS without causing mutation

In my program, I store an array of objects containing meta information. This is the format for each object. this.state.slotData [{ availability: boolean, id: number, car: { RegistrationNumber : string, ...

Encountering numerous errors while attempting to upgrade from Angular 9 to Angular 11

On Thursday of last week, I initiated an Angular update and unfortunately, I have been encountering numerous errors ever since. The most recent error while running ng serve -o is: An unhandled exception occurred: ENOENT: no such file or directory, lstat &a ...

Tips for activating automatic building of packages when utilizing pnpm install?

Our unique project is utilizing a combination of pnpm, workspace, and typescript in adherence to the monorepo standard. Upon cloning the repository, we execute a pnpm install command to download dependencies and establish links between local packages. De ...

What is the best way to transform a string into an array?

After receiving an object from the http response, it looks something like this: {"[3, company1]":["role_user"], "[4, company2]":["role_admin"] } The key in the object is represented as an array. Is there a method in ...

Angular: how to manually trigger change detection without using Angular's dependency injection system

Is there a way to globally initiate angular change detection without having to inject something like ApplicationRef? I am looking to utilize the functionality as a standard JavaScript function rather than a service method, in order to avoid the need for ...