Unexpected behavior observed in ng-select when pasting search values

When attempting to update an array of strings acting as the model for an ng-select, the values do not appear correctly in the search box.

https://i.sstatic.net/WqdJ6.png

The values that are displaying correctly are the ones selected from the dropdown menu. However, the numbers I manually add to the list do not display properly.

Select box in template:

<ng-select
 id="oNumberSelect"
 [items]="ownerNumberResults | async"
 [typeahead]="typeAhead$"
 bindLabel="desc"
 bindValue="code"
 dropdownPosition="bottom"
 [(ngModel)]="selectedOwnerNumbers"
 (ngModelChange)="handleSelectionChange()"
 [multiple]="true"
 [searchable]="true"
 multiple="true"
 style="overflow-y: auto; width: 100%"
 appendTo="body"
 (paste)="handlePaste($event)"
 minTermLength="3"
 [addTag]="true"
   >
</ng-select>

Referenced methods:

handlePaste(pasteEvent: ClipboardEvent): void {
 pasteEvent.stopPropagation();
 pasteEvent.preventDefault();
 const clipStrings:string[] = [...pasteEvent.clipboardData.getData('Text').trim().split(/[\s,)]+/)]

 this.selectedOwnerNumbers = [...this.selectedOwnerNumbers, ...clipStrings];
}

searchOwnerNumbers(): void {
 this.ownerNumberResults = this.typeAhead$.pipe(
  distinctUntilChanged(),
  debounceTime(500),
  switchMap(term => {
    return this.ownerHttpService.searchOwnerProperty('ownerNumber', term);
   }
  )
 );
}

handleSelectionChange(): void {
 console.log(this.selectedOwnerNumbers)
}

Select variables:

selectedOwnerNumbers: string[];
typeAhead$ = new Subject<string>();
ownerNumberResults: Observable<Option[]>;

I have attempted various techniques such as using sets and different array arrangements but I am unable to get the pasted values to display correctly in the UI.

Answer №1

It is common for this issue to occur when the bindValue and bindLabel do not match.

Consider adjusting the handle paste logic as shown below:

  handlePaste(pasteEvent: ClipboardEvent) {
    pasteEvent.stopPropagation();
    pasteEvent.preventDefault();
    const clipStrings: string[] = [
      ...pasteEvent.clipboardData
        .getData('Text')
        .trim()
        .split(/[\s,)]+/),
    ];
    this.selectedOwnerNumbers.push(this.ownerNumberResults.find(result => result.desc === clipStrings[0]).code);
    this.selectedOwnerNumbers = [...this.selectedOwnerNumbers]
  }

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

A guide on rendering a JSON array received from a URL using AJAX in AngularJS

Upon receiving a JSON array from the following URL: , it appears like this:https://i.stack.imgur.com/1Xrf4.png Within my AngularJS controller, I have the following code: $('#example-1').DataTable({ "ajax" : 'http://blahblahbla ...

You are unable to use multiple background colors on a material UI snackbar

Is there a way to apply multiple background colors to a material UI snackbar? I attempted using linear-gradient as shown below, but it didn't work. import Snackbar from 'material-ui/Snackbar'; const bodyStyle = { border: `2px solid ${co ...

Maintain the modifications in NPM software dependencies

Currently, I am developing a REACT web application and have integrated the react-datasheet library using NPM. To ensure compatibility with IE11, I made modifications to the JavaScript file installed via NPM. While these changes work perfectly on my local m ...

Iterate through the object received from the node promise and pass it to the subsequent .then method

After grappling with this issue for what feels like an eternity, I find myself immersed in learning about Node.js and trying to grasp the concept of promises. My current challenge involves retrieving data from the Spotify API, starting with fetching my ow ...

Guide on creating a JSONP request

My goal is to perform cross-site scripting. The code snippet below shows the jsonp method, which appears to fail initially but succeeds when switched to a get request. I am trying to achieve a successful response using the jsonp method. I have confirmed th ...

Transform the components of an array into a mathematical formula and store it in a variable

I am working with an array that contains boolean values (True, False) and strings representing logical operators (‘and’, ‘or’, ‘not’). For example: array = [True, 'and', False] I want to convert these elements into an actual express ...

Invoking a method in Vue.js from another component

I'm just starting out with VUE and I have a unique challenge for my project. I want to have a button on one page that triggers a function on another page. I know some may ask why not keep the button and function on the same page, but I am exploring ho ...

Error encountered: Index 109 - The function $.ajax(...).success is not recognized as a valid function while working with jQuery in a Node

I'm just starting to learn about jquery and have been experimenting with ajax in my recent code. Below is the snippet of what I have implemented: $(function(){ $("#status").change(function(){ if($(this).is(':checked')) ...

The drop-down menu keeps flickering instead of remaining open when clicked

I am facing an issue with a dropdown menu in my webpage. The menu is initially hidden, but should become visible when the list element containing it is clicked. I have written JavaScript code to add a class that changes the visibility property to visible u ...

Clipanion is unable to fulfill requests

I followed the official Clipanion documentation for creating a CLI tool () and even cloned an example from here - https://github.com/i5ting/clipanion-test, but I'm facing issues when trying to execute my commands. It seems like I might be struggling ...

Encountering an unexpected token 'Indent' while working with Jade in Eclipse

Currently, I am delving into the world of node, angular, javascript, express, and jade. Transitioning from a purely .net based coding environment has presented me with quite the learning curve. While following a tutorial, I encountered a roadblock at step ...

Display a text field when the onclick event is triggered within a for

Control Panel for($i = 1; $i <= $quantity; $i++){ $data .= '<b style="margin-left:10px;">User ' . $i . '</b>'; $data .= '<div class="form-group" style="padding-top:10px;">'; $data .= ' ...

Exploring Angular's Parsing Function ($parse)

Currently, I am working on an AngularJS component that takes a string template as input and compiles it using the following code snippet. Later, I use this compiled template to render different items: this.$parse(template); While trying to achieve someth ...

What is the most suitable Vue.js component lifecycle for data retrieval?

I recently came across an article on Alligator.io discussing the drawbacks of using the mounted lifecycle in Vue for HTTP requests. This got me thinking, are there any best practices or guidelines for fetching data from APIs in Vue.js? ...

JavaScript DateTimePicker onChange event malfunctioning

Issue with JS datetimepicker onChange event not functioning. Attempts have been made using OnSelect, OnClose, OnChange, OnHide, OnChangeMonth to trigger the datetimepicker event, but none of them seem to be effective. <input type="text" class="form-co ...

Next.js optimizes the page loading process by preloading every function on the page as soon as it loads, rather than waiting for them to

My functions are all loading onload three times instead of when they should be called. The most frustrating issue is with an onClick event of a button, where it is supposed to open a new page but instead opens multiple new pages in a loop. This creates a c ...

Create personalized styles for each item within a stack with specific spacing using the @mui library

Is there a way to change both the background color and spacing area when hovering over each item in my list? https://i.stack.imgur.com/87TST.png <Stack spacing={4} divider={<Divider variant={`fullWidth`} orientation={`horizontal`} flexItem/>}> ...

Generate an array using the properties of an object

Seeking a more efficient way to configure settings for an app using objects? Consider starting with the following object: var obj = { property_one: 3; property_two: 2; property_three: 1; } And transforming it into the desired array format: v ...

Using a snapshot test with MenuItem from material-ui is not compatible with Jest

I am facing an issue while trying to perform a snapshot test with jest on a component that utilizes typescript, react, and material-ui. Specifically, the MenuItem component from material-ui is throwing an Invariant Violation: getNodeFromInstance: Invalid a ...

Implementing dynamic input elements in React components and managing state changes

I am currently working on a React component that includes simple input fields to track state for an AJAX call. There is also a button that, when clicked, generates a new set of input fields identical to the original ones. As a React novice, I initially at ...