Search code examples
angulartypescriptangular-ngselect

ng-select property ClearSearchOnAdd not working as expected


I am working on ng-select and trying to bind pasted items. I am trying to paste items with space separator like

html:

<ng-select #ngSelect
[items]="people"
[multiple]="true"
bindLabel="name"
[closeOnSelect]="false"
[clearSearchOnAdd]="true"
bindValue="id"
[(ngModel)]="selectedPeople"
(paste)="onPaste($event)">
<ng-template ng-option-tmp let-item="item" let-item$="item$" let-index="index">
    <input id="item-{{index}}" type="checkbox"    [ngModel]="item$.selected"/> {{item.name | uppercase}}
</ng-template>
   </ng-select>
   </br>
   <small>{{selectedPeople | json}}</small>

TS:

export class MultiCheckboxExampleComponent implements OnInit {

people: Person[] = [];
selectedPeople = [];
@ViewChildren('ngSelect') ngSelect:ElementRef;
constructor(private dataService: DataService,private el:ElementRef) {
}

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

   onPaste(event: ClipboardEvent) {
let clipboardData = event.clipboardData;
let pastedData = clipboardData.getData('text');
    // split using spaces
    var queries = pastedData.split(/\s/);
    //var source = mtc.itemsSource;
    // iterate over each part and add to the selectedItems
    queries.forEach(q => {
     var cnt = this.people.find(i => i.name.toLowerCase() === q.toLowerCase());
     if(cnt != undefined)
     {
         this.selectedPeople = [...this.selectedPeople, cnt.id];
        //this.selectedPeople = [this.people[0].id, this.people[1].id];
    }});
//console.log(pastedData);
 }

  }

Items selected successfully from checkbox list but pasted items are still present with selected items. enter image description here

How I can prevent the pasted items so they will not visible with selected items.


Solution

  • I used the blur event once paste event successfully completed:

     let nodes: NodeListOf<HTMLElement> = document.querySelectorAll(
          ".ng-input input"
        ) as NodeListOf<HTMLElement>;
        for (let i = 0; nodes[i]; i++) {
          (nodes[i] as HTMLElement).blur();
        }
    

    Using this I am able to solve the issue.