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

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

Refresh the main state by integrating the feature state using NGRX

A question arises regarding my app that utilizes ngrx to display blogs. Here is an overview of the main root state: import { Blog } from '../models/blog'; export interface AppState { readonly loaded: boolean; readonly blogs: {[key:number]: ...

Encountered a Next-Auth Error: Unable to fetch data, TypeError: fetch failed within

I've been struggling with a unique issue that I haven't found a solution for in any other forum. My Configuration NextJS: v13.0.3 NextAuth: v4.16.4 npm: v8.19.2 node: v18.12.1 When the Issue Arises This particular error only occurs in the pr ...

Is it acceptable to have an empty dependency array in React.useEffect?

Within my child React component, I receive an itemList prop from the parent component. This prop is an array of objects that contain data fetched from an endpoint. My goal in the child component is to enhance each object in the itemList array by adding mo ...

Choosing a single item from multiple elements in React using React and typescript

In this particular project, React, TypeScript, and ant design have been utilized. Within a specific section of the project, only one box out of three options should be selected. Despite implementing useState and toggle functionalities, all boxes end up bei ...

p-menu fails to appear

I'm currently experimenting with Primeng and Angular 2 to put together a basic menu. Take a look at my code snippet: import {Component, OnInit} from '@angular/core'; import {Menu, MenuItem} from 'primeng/primeng'; @Component({ ...

Can you share the appropriate tsconfig.json configuration for a service worker implementation?

Simply put: TypeScript's lib: ['DOM'] does not incorporate Service Worker types, despite @types/service_worker_api indicating otherwise. I have a functional TypeScript service worker. The only issue is that I need to use // @ts-nocheck at t ...

Validate if the program is currently running as "ionic serve" before implementing a conditional statement

Is there a method to determine if the ionic serve CLI is currently active (indicating it's not running on a physical device) within the code and use it as a condition? My problem: I have a Cordova plugin that returns a response to Cordova. When usin ...

Storing Buffer data in Postgres bytea using TypeORM is limited to only 10 bytes

I am encountering an issue while trying to store images in a postgres database, as only 10 bytes of data are being saved. Here is the sequence of events: Initially, I receive a base64 encoded string on my server. I then convert it into a Buffer, assign i ...

Developing a REST API for a component with 18 interconnected elements

Currently, I am developing a REST API to expose a table to an Angular frontend, and I've encountered a unique challenge: The data required for display is spread across 10 different tables besides the main entity (referred to as "Ticket"). Retrieving t ...

retrieve data from the server

Currently, I am delving into the world of Angular with ASP.NET Core 3.0 and still relatively new to it. Here's my scenario - I have a function that is able to save PDF files in a specific folder called "Resources\PdfFiles" within the ASP.NET back ...

How can I pass additional props that are not specified in the interface while working with a React TS component?

I am working with a TS React component called MyButton.tsx: import React from 'react' interface MyButtonProps { children: JSX.Element | JSX.Element[], className?: string, variant?: 'big-button' | 'medium-button' | &apos ...

When comparing TypeScript index signatures to Record<Keys, Type> return type, the focus is on handling objects with unspecified properties

I have a function called getQueryParams that takes a string as input and returns an object with unknown properties: function getQueryParams(s) { if (!s || typeof s !== 'string' || s.length < 2) { return {} } return s .substr(1) ...

After a duration of 4 minutes, an ERR_EMPTY_RESPONSE is thrown in response to the

My angular 5 node app involves sending a request to the server and waiting for a response. There are instances where the response takes around 5-6 minutes to arrive. However, an ERR_EMPTY_RESPONSE error is triggered by the http method after just 4 minutes ...

Updating data within rows in Angular 4

Is there a way for me to update the value in my row based on a selected ingredient from a dropdown list? I want the unit price to be patched into the input field when a specific ingredient is chosen. You can find the relevant code snippets by visiting TH ...

Join and Navigate in Angular 2

Attempting to retrieve information from a JSON file has been an issue for me. Here is the code snippet: ngOnInit() { this.http.get('assets/json/buildings.json', { responseType: 'text'}) .map(response => response) .subsc ...

Encountering a Zone.js error when trying to load an Angular 7 app using ng serve, preventing the application from loading

Scenario: Yesterday, I decided to upgrade my Angular app from version 5.2.9 to 6 and thought it would be a good idea to go all the way to 7 while I was at it. It ended up taking the whole day and required numerous changes to multiple files, mostly due to R ...

I'm unable to resolve all parameters for xxx -- unit testing using jest

I recently encountered an issue with a test in jest that is failing and displaying the following error message: Error: Can't resolve all parameters for LoginService: (?). at syntaxError (/Users/wilson.gonzalez/Desktop/proyecto_andes/external/npm/nod ...

Adding Rows Dynamically to Material Data Table in Angular 7

Is there a way to dynamically add data from a service into my table? I am receiving data from AuthenticationService dialog and attempted using this.dataSource.push(this.transaction);, but it did not work as expected. This is the code snippet where I trie ...

Advanced Angular2 Services Expansion

I'm looking to enhance an existing angular service (for example, Http). Requirements: The extension of the service should be done through angular's dependency injection It should be possible to extend the service multiple times using a pattern ...

Creating a typescript type for contextual dispatch by leveraging the values of another interface

I am seeking to define a specific type for my "reducer" function. The "reducer" function I have takes in 2 parameters: the current state and the data sent in the dispatch context (to be used by the reducer). const reducer = ( state: any, props: { ...