skip to Main Content

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.

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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'];
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search