how to display dynamic data as selected in ng-select with search dropdown?

389 Views Asked by At
let options= \[{value: 'a', id:1},{value:'b',id:2}\];

let items=\[\]; 

I will be binding this data to ng select with search in ng-options

<ng-select [items]="options"
  bindLabel="value"
  bindValue="value"
  [multiple]="true"
  placeholder="Search for..."
  [(ngModel)]="items"
  (change)="changeFn($event,false)"
  [hideSelected]="true"
  
  >
<ng-template
        ng-option-tmp
        let-item="item"
        let-item$="item$"
        let-index="index"
      >
        <div class="row">
            <span class="text-muted" >Task filter: {{ item['value'] }}</span>
        </div>
      </ng-template>

            
</ng-select>

on click of a button i wanted to push some dynamic data like

function(){
   this.item.push({value: 'c', id:3}\];  
}

i wanted to display value c as selected in the ng-select how can i make that possible

i have no idea how to make it work. can anyone help me to make it work.
Thanks in advance.

3

There are 3 best solutions below

0
Yong Shun On

According to the documentation (Change Detection section),

Ng-select component implements OnPush change detection which means the dirty checking checks for immutable data types.

You should update the array's value for both options and items instead of performing object mutation.

add() {
  this.options = [...this.options, { value: 'c', id: 3 }];
  this.items = [...this.items, 'c'];
}

Demo @ StackBlitz

0
Rahul Sahu On

You can use 3 different techniques here.

  1. Run change detection forcefully after making changes in your object.
import { ChangeDetectorRef } from '@angular/core';

constructor(private cdr: ChangeDetectorRef) {}

this.cdr.detectChanges();

  1. Use change detection strategy onPush, here even if you make changes in inside object then change Detection will run automatically.
import { ChangeDetectionStrategy, OnChanges, OnInit } from "@angular/core";
@Component({
  selector: "app-your-component",
  templateUrl: './your-component.component.html',
  styleUrls: ["./your-component.component.scss"],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class YourComponent implements OnChanges, OnInit  {}
  1. You can also reassigned modified object using spread operator
add() {
  this.options = [...this.options, { value: 'c', id: 3 }];
  this.items = [...this.items, 'c'];
}
0
Nizar On

There is a simple way that works for me, just refresh items in your function adding

function(){
this.items.push({value: 'c', id:3}];
//add here 
this.items = this.items.slice();
}