0

I am trying to implement multiselect using ng2-select Here is may view block code,

<ng-select 
            [multiple]="true" 
            [items]="items" 
            [disabled]="disabled" 
            (data)="refreshValue($event)" 
            (selected)="selected($event)" 
            (removed)="removed($event)"
            placeholder="Select from list"></ng-select>

and in component I have items list and selected value list

 private value:any = [{id: "1", text: "User A"}];
  private items:Array<Object> = [{id: "1", text: "User A"},{id: "2", text: "User B"},{id: "3", text: "User C"}];

  private selected(value:any) {
    console.log('Selected value is: ', value);
  }

  private removed(value:any) {
    console.log('Removed value is: ', value);
  }

  private refreshValue(value:any) {
    this.value = value;
  }

How can I achieve "select all" and "unselect all" functionality in it and ng-select is not populate select item in view.

Sach
  • 554
  • 5
  • 14
  • Can't post a duplicate answer to a duplicate question even though this is the older post so if you need an answer see https://stackoverflow.com/a/54544217/1148107 – mtpultz Feb 06 '19 at 02:42

1 Answers1

0

The value that is passed into the removed and and selected function is of type EventEmitter<SelectItem>,hence to invoke this function(removed or selected) manually in your component,you can call it as many times as you want.Therefore,to unselect all,we need to loop through the total number of items and call removed() function while passing the appropriate parameter accordingly. We repeat the same procedure for selectAll() function,but in this instance,we will call select() function in the loop instead.Below is the breakdown of the code.I have not tested this,but this should work.

unselectAll():void {
  for(let i:number=0;i<items.length;i++){
     this.removed(items[i]);//we remove each SelectItem by invoking the removed function for each loop  
   }
} 

selectAll():void {
  for(let i:number=0;i<items.length;i++){
     this.selected(items[i]);  //we select the SelectItem by invoking the selected function for each loop
   }
} 
Rbk
  • 72
  • 1
  • 11