optimistex / ngx-select-ex

Angular based replacement for select boxes
https://optimistex.github.io/ngx-select-ex/
MIT License
111 stars 42 forks source link

Dynamic update multiple select #150

Closed GazousGit closed 5 years ago

GazousGit commented 5 years ago

Hello and thank you for your amazing work on this fork.

I'm using Angular 7 and Bootstrap 4 and I had some issue with the ng2-select component, yours matches all I wanted to do/fix, wonderfull!

However I'm facing a tiny Issue with the multiselect (this is close to #116 )

So here it is, I got a Multiselect binded to a form within a modal:

  <ngx-select id="Person"
              size="default"
              formControlName="person"
              [defaultValue]="currentPerson"
              [allowClear]="true"
              [multiple]="true"
              [items]="persons"
              noResultsFound="No Person found matching your query"
              placeholder="Please select someone">
  </ngx-select>

I have (in this modal), a nested modal which allows me to add a new Person. uppon successfull add, it'll return the new Person object, I can add it to the [items] and find it in the dropdown, however I would like it to be set as [defaultValue].

Here's what I tried:

  this.persons.push({id: receivedEntry._id, text: receivedEntry.email});
  this.ArchiveForm.controls.person.value.push(receivedEntry._id);

  this.currentPerson.push({id: receivedEntry._id, text: receivedEntry.email});
  this.currentPerson= JSON.parse(JSON.stringify(this.currentPerson));

(The JSON.Parse line was necessary on the ng2-select component, in order to refresh the active items) (i've tried updating the currentPerson with only the _id, but it doesn't change much).

It doesn't seems to work, both arrays got their value but the ngx-select doesn't show the new selected value.

Did I miss Something ? Or is there a better way to set the defaultValue / ActiveItems ?

Thanks and have a great day!

GazousGit commented 5 years ago

Nevermind, here's what I found:

    const data = this.ArchiveForm.controls.person.value;
    data.push(receivedEntry._id);
    this.ArchiveForm.controls.person.setValue(data);

So the formControls is constant I wasn't able to push the new id inside it, I had to use setValue Func in order to have it "refresh" the form data (this has been done this way in case your multiselect has already some option selected and you want to create&push a new one directly without losing the previously selected ones)

I'll mark it as resolved but if anyone think I could do better, I'll be glad to hear your answer :-D