The method for linking ng-select to varied items is determined by the filter being used

Below is the code snippet I am using to bind an ng-select present in a formgroup.

HTML:

<p>Select multiple elements using paste</p>
 <div class="col-md-offset-2 col-md-4">  
             <select style="widht:300px;" [ngModel]="selectedSearchFilter" (ngModelChange)="onChange($event)" name="sel3">
              <option [ngValue]="i" *ngFor="let i of searchFilters">{{i.name}}</option>
            </select>
        </div>  
<br>

<form class="form-horizontal" [formGroup]="personalForm" (ngSubmit)="onSubmit()">
<div style="background-color: gainsboro">  
   <div formArrayName="other" *ngFor="let other of personalForm.get('other').controls; let i = index" class="form-group">  
        <div [formGroupName]="i">  
              <div class="form-group" class="row cols-md-12">  
                <ng-select #ngSelect formControlName="searchCreteria"
                    [items]="people"
                    [multiple]="true"
                    bindLabel="name"
                    [closeOnSelect]="false"
                    [clearSearchOnAdd]="true"
                     bindValue="id"
                    (paste)="onPaste($event,i)"
                    (clear)="resetSearchCreteria(item)"
                    [selectOnTab]="true"
                    [closeOnSelect]="true">
                    <ng-template ng-option-tmp let-item="item" let-item$="item$" let-index="index">
                        <input id="item-{{index}}" type="checkbox"/> {{item.name | uppercase}}
                    </ng-template>
                </ng-select>
              </div>
        </div>  
    </div>  
</div>  
<button class="btn btn-primary" type="button"
       (click)="onClearDataClick()">Clear Data</button>
  </form>
  {{selectedSearchFilter | json}}

.ts:

import { Component, OnInit,ViewChildren,ElementRef } from '@angular/core';
import { DataService, Person } from '../data.service';
import { map } from 'rxjs/operators';
import { FormGroup, FormArray , FormControl, FormBuilder,Validators } from '@angular/forms';

@Component({
selector: 'multi-checkbox-example',
templateUrl: './multi-checkbox-example.component.html',

})
export class MultiCheckboxExampleComponent implements OnInit {

people: Person[] = [];
selectedPeople = [];

ngSelectCount=[];
personalForm:FormGroup;

searchFilters = [
   { name: "--Please Select Item", id: -1 },
{ name: "Country", id: 1 },
{ name: "States", id: 2 },
{ name: "Cities", id: 3 }];
selectedSearchFilter = this.searchFilters[0];
constructor(private dataService: DataService,private formBuilder: FormBuilder) {

}

 ngOnInit() {
  this.personalForm = this.formBuilder.group({
      filter: new FormControl(null),
      other: this.formBuilder.array([])  
    });
 }

  addOtherSkillFormGroup(filterName:string): FormGroup { 

      this.dataService.getRecords(filterName)
        //.pipe(map(x => x.filter(y => !y.disabled)))
        .subscribe((res) => {
            this.people = res;
            
            //this.selectedPeople = [this.people[0].id, this.people[1].id];
        });

   return this.formBuilder.group({  
    searchCreteria: [''] 
   });  
  }  

  onPaste(event: ClipboardEvent,i:any) {
  let clipboardData = event.clipboardData;
  let pastedData = clipboardData.getData('text');
    // split using spaces
    //var queries = pastedData.split(/\s/);
    var queries = pastedData.split(/\r\n|\r|\n/);
    //console.log(queries);
    // iterate over each part and add to the selectedItems
    queries.forEach(q => {
     var cnt = this.people.find(i => i.name.toLowerCase() === q.toLowerCase());
      console.log(cnt);
     if(cnt != undefined)
     {
        const control = <FormArray>this.personalForm.controls.other;
        const controlData = control.get([i]);
        controlData.get('isPointChecked').setValue(true);
        this.people[i]['isPointChecked'] = true;
    }});
   }
   onClearDataClick() {
    this.personalForm.reset();
  }
 onChange(e)
 {
  if(e.id != -1)
  {
   var cnt = this.ngSelectCount.find(i => i === e.id);
     if(cnt == undefined)
     {
       console.log(e.id);
      (<FormArray>this.personalForm.get('other')).push(this.addOtherSkillFormGroup(e.name));  
        this.ngSelectCount.push(e.id);
        this.selectedSearchFilter = e;
     }
  }
  else
  {
    this.personalForm.reset();
    this.ngSelectCount.length = 0;
   }
}

resetSearchCreteria(e)
{
  const index: number = this.ngSelectCount.indexOf(e);
  if (index !== -1) {
    this.ngSelectCount.splice(index, 1);
  } 
}
/////////////////////////////

}

data.service.ts:

import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { delay, map } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';

export interface Person {
id: any;
name: string;
}

@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) { }
getRecords(term: string = null): Observable<Person[]> {
    let items = this.getData(term);
    return of(items).pipe(delay(200));
}

getData(filterType: string) {
if (filterType == "Country") {
  return [
    { id: 1, name: "India" },
    { id: 2, name: "Switzerland" },
    { id: 3, name: "Norway" },
    { id: 4, name: "Macao" },
    { id: 5, name: "Qatar" },
    { id: 6, name: "Ireland" },
    { id: 7, name: "United States" },
    { id: 15, name: "United Kingdom" },
    { id: 21, name: "United Arab Emirates" }
  ];
} else if (filterType == "States") {
  return [
    { id: 1, name: "State 1" },
    { id: 2, name: "State 2" },
    { id: 3, name: "State 3" },
    { id: 4, name: "State 4" },
    { id: 5, name: "State 5" },
    { id: 6, name: "State 6" },
    { id: 7, name: "State 7" },
    { id: 15, name: "State 8" },
    { id: 21, name: "State 9" }
  ];
} else {
  return [
    { id: 1, name: "City 1" },
    { id: 2, name: "City 2" },
    { id: 3, name: "City 3" },
    { id: 4, name: "City 4" },
    { id: 5, name: "City 5" },
    { id: 6, name: "City 6" },
    { id: 7, name: "City 7" },
    { id: 15, name: "City 8" },
    { id: 21, name: "City 9" }
  ];
  }
}
}

In the above code, I am attempting to bind different items based on dropdown selection. If the user selects "Country," then countries will be bound with ng-select, and if states are selected, then states will be bound. However, in my case, the last selection is reflecting for all form controls.

You can find a complete working sample here

Can you please assist me in configuring this case?

Answer №1

Why was my response marked as deleted? I put in a lot of effort to create this demo, only to have my post removed without any explanation.

After extensive research and reading various tutorials, I finally managed to implement the feature of selecting multiple items using copy and paste.

To see it in action, please visit the following link: Angular MultiSelect

Thank you for all your feedback and suggestions.

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

Utilizing internationalization and next/image in next.config.js alongside TypeScript

Currently, I am in the process of developing a miniature application using TypeScript within NextJS now that support for TypeScript comes standard in Next.js. Additionally, my aim is to integrate two recently introduced features: Image Component and Image ...

What is the best way to integrate Circles into a line chart using the "d3.js" library?

I am encountering an issue with the placement of circles in a line chart created using d3.js. The circles are not appearing at the correct position on the chart. How can I troubleshoot and resolve this problem? My development environment is Angular, and t ...

most effective method to link table header to corresponding table row within this specific data organization

In my current project, I have a table component that relies on two data structures to create an HTML table: one for the table schema (paymentTableMetadata) and one for the table data (paymentTableData). To simplify the process, I have hardcoded these data ...

What is the solution to resolving the websocket.onclose issue in Thirdweb?

I'm a beginner with next.js and I'm currently working on a website that utilizes web3 technology, so I need to incorporate thirdweb. My first step was running the following command to add thirdweb to my project: yarn add @thirdweb-dev/react @thi ...

Is it possible for a Docker container to automatically back up its content before launching?

Currently, I am facing a challenge with my Docker setup for an Angular project. The issue arises when the node packages are not already installed, causing it to fail when someone tries to start it after cloning. This is due to the fact that node packages a ...

How to access custom parameters set in middleware in Next.js server actions?

I'm currently utilizing middleware.ts to intercept and authenticate user requests. However, I want to include data from our database in these authenticated requests. Within my server action code, the structure is as follows: export async function get ...

Selecting the optimal data structure: weighing the benefits of using boolean check versus array .include (balancing performance and redundancy

My objects can have one or more properties assigned, with a total of 5 different properties in my case. To illustrate this, let's use a simple movie example where each movie can be assigned from 5 different genres. I have come up with two methods to ...

Setting up Vue CLI 4 for optimal development: Integrating ESLint, Prettier, Airbnb rules, TypeScript, and Vetur

When starting a new project using Vue CLI v4.0.5 and selecting options for TypeScript and Linter / Formatter, you will be presented with pre-configured choices for linting and formatting: ? Choose a linter / formatter configuration: (Use arrow keys) > ...

Determine whether a many-to-many relationship involves a specific entity

I am currently working on developing an API for managing surveys. One challenge I'm facing is determining whether a specific user has moderation privileges for a particular survey. A many-to-many relationship has been set up between the two entities. ...

How can one dynamically import external modules in webpack?

Is there a way to dynamically import webpack modules from an external URL into a JavaScript application that is compiled with webpack? If it is possible, what is the correct method to do so? ...

Show intricate key-value pairs in AG-Grid

I have a map containing date keys and lists of objects as values that I need to send to Angular via an API. My goal is to display this map in ag-grid for sorting based on the "amt" field. The structure of the map is as follows: { 2019-12-23 00:00:00.0: Ar ...

Using various date formats on dual datepicker controls within a single Angular component

I am facing an issue where I need to have two datepickers on the same view with different date formats. One should display month/year, and the other month/day/year. However, due to restrictions from the provider, both controls are using the same date forma ...

Error TS2339: The member 'sort' is not found in the type 'BehaviorSubject<AbstractControl[]>'

Looking to create a dynamic table using Angular material where I can dynamically add or remove data. As a newcomer to Angular, I found the following StackBlitz helpful in setting up the table: https://stackblitz.com/edit/angular-material-editable-table-fa ...

Combine data from a new observable with the existing data in Angular using RxJS

I have a list stored as an observable[]. To subscribe to it in the template, I am using async. Each time I scroll, this method is called: onScroll() { this.list$ = this.list$?.pipe( tap((list) => { this.notificationService . ...

Tips on how to properly send a post request in Angular using a method similar to Postman and the application/x-www

Currently, I am working on an Angular client application for a Django API project. One of the endpoints in the API accepts requests formatted as application/x-www-form-urlencoded, which contain both file and string data. To test this endpoint, I used POSTM ...

Extending a Svelte component with a P5JS class: A step-by-step guide

As a newcomer to SO, I haven't asked many questions before, so please bear with me if I don't entirely follow the guidelines. I'll do my best to explain the issue at hand. In my project, I am utilizing Sveltekit (create-svelte) and P5JS (p5 ...

What is the best way to add an item to an array with distinct properties?

I am currently working on creating an array with different properties for each day of the week. Here is what I have so far: const [fullData, setFullData] = useState([{index:-1,exercise:''}]) My goal is to allow users to choose exercises for a sp ...

Determine the accurate data types while transforming an array into an object using a specific key

I have an array of elements, each with a unique category string property. I aim to transform this into a structure where the category serves as the key and the original element is the value. To tackle this, I first verify that I possess a correctly typed ...

A guide to adjusting the font size and placement of text in a precise manner

Is there a way to adjust the font size and position in a particular text? How can this be achieved? doc.text( 40, 30, "jspdf" ); https://i.stack.imgur.com/Io7RE.png ...

How to eliminate subdomains from a string using TypeScript

I am working with a string in TypeScript that follows the format subdomain.domain.com. My goal is to extract just the domain part of the string. For example, subdomain.domain.com should become domain.com. It's important to note that the 'subdoma ...