Search code examples
javascriptangularangular-ngselect

ng-select not updating in Angular 2


hello i am new in angular 2

i can make formGroup in add in ng-select controll and predefine value added.

that is perfectly. but when button click then new value push in ng-select but ng-select not updating .

here my plunker

https://plnkr.co/edit/Hwfk1T2stkiRcLTxuFmz

//our root app component
import {Component, OnInit, NgModule, ViewChild} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {FormControl, FormGroup, ReactiveFormsModule} from '@angular/forms';
import {SelectModule} from 'ng-select';

@Component({
    selector: 'my-app',
    template: `
<h1>ng-select demo app</h1>
<form style="padding:18px;max-width:800px;"
    [formGroup]="form">

    <div style="margin:5px 0;font-weight:600;">Single select example</div>
    <ng-select
          [options]="options0"
          [multiple]="false"
          placeholder="Select one"
      formControlName="selectSingle"
     >
    </ng-select>

   <button (click)="pushValue()">Click</button>



    <div>Events:</div>
    <pre #preSingle>{{logSingleString}}</pre>

</form>`
})
export class App implements OnInit {

    form: FormGroup;

    multiple0: boolean = false;
    options0: any[] = [];
    selection: Array<string>;

    @ViewChild('preSingle') preSingle;

    logSingleString: string = '';

    constructor() {
      this.options0.push({"label":'test',"value":'Test'});
       console.log("Object:::"+JSON.stringify(this.options0));
    }

    ngOnInit() {
        this.form = new FormGroup({});
        this.form.addControl('selectSingle', new FormControl(''));
        console.log("Object:::"+JSON.stringify(this.options0));
    }

    pushValue()
    {
       console.log("pushValue call.");
       this.options0.push({"label":"test","value":"Test"});
       console.log("Object:::"+JSON.stringify(this.options0));
    }
}

@NgModule({
  imports: [
    BrowserModule,
    ReactiveFormsModule,
    SelectModule
  ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

where is wrong ???


Solution

  • Looking at ng-select source code i noticed

    ngOnChanges(changes: any) {
      if (changes.hasOwnProperty('options')) {
         this.updateOptionsList(changes['options'].isFirstChange());
      }
    

    so in order to update options list you should fire ngOnChanges. It can be done by creating new reference to options0

    this.options0 = this.options0.concat({"label":"test","value":"Test"});
    

    or

    this.options0 = [...this.options0, {"label":"test","value":"Test"}];
    

    Modified Plunker