3

I am using ng-select and specifically using typeahead to fetch the list from the server as user types. Following example as described in typeahead example : people3$. My requirement is to add value when user clicks a button (I have id and label and corresponding object) but I am failing to understand :

  1. How can I push Item to item : Observable<any[]> I tried doing this.item = concat(of([{label:this.field.display,id:value}])) it pushes the value but it does not reflect the value in ng-select until I click somewhere else outside the element.
  2. I tried this solution by @ViewChild and on this.ngSelect.items = [{label:this.field.display,id:value}] still it does not show value in ng-select.

error

After adding value in group, I have added the object but still it does not shows, If i click anywhere soon value will be shown.

I want to know

  1. What possibly can be the reason for this behaviour.
  2. preferred way to push items in Observable<any[]>

Here is my ng-select configuration :

<ng-select class="form-control ng-select-padding"
                 [items]="referenceItems | async"
                 [hideSelected]="true"
                 [loading]="searchFailed"
                 [typeahead]="searchReferenceItems"
                 bindLabel="label"
                 bindValue="id"
                 (change)="setField($event)"
                 (blur)="onUpdated()"
                 [formControlName]="field.name" ngDefaultControl>
      </ng-select>

//@ TS file

searchReferenceItems =  new Subject<object>();
referenceItems: Observable<any[]> ;

Thanks for your kind help

Mohd. Monis
  • 199
  • 4
  • 18
  • is there any error in your console? – Nithya Rajan Mar 03 '19 at 16:32
  • No, there is no error as such – Mohd. Monis Mar 03 '19 at 16:39
  • "it pushes the value but it does not reflect the value in ng-select until I click somewhere else outside the element." The observable *ISN'T* the value. Think of it as a "placeholder" to let you know "when something happens". "Nothing changes" until "something happens"! Q: Make sense? – paulsm4 Mar 03 '19 at 18:04

1 Answers1

1

The observable must be notified by the next function you can use a BehaviorSubject and the function asObservable() to show the elements.

   subject = new BehaviourSubject<any>([]) 
   referenceItems = this.subject.asObservable(); 

Then when ever you want to update the value you can use the 'next' function to the subject.

   this.subject.next(this.subject.value.concat({id:..., label:...}));
Abel Valdez
  • 2,368
  • 1
  • 16
  • 33