Giter Site home page Giter Site logo

Comments (2)

marco-silva0000 avatar marco-silva0000 commented on June 25, 2024

I have the same problem, were you able to fix it?

I'm trying to create a wrapper component that is a select2 with options that are always the same to be used in different components, but I'm also stuck in setting the initial value for this scenario, it works fine when I just use the raw [ngModel] but not in my wrapper

from ng-select2.

alexaka1 avatar alexaka1 commented on June 25, 2024

I think you might find this helpful. #32

The way select2 works, is that it wraps a regular html select with a fancy user interface. However changing the underlying select does absolutely nothing to the select2 interface, you have to tell it to update with the default data. So if you're using FormGroup with ng-select2, then the underlying select correctly has your default value, but ng-select2 does not show this to you.

If you have server side data like I do, then it's even more difficult, because the actual options don't exist on the client side, so there is nothing to select with the underlying html select. Hence the issue I referenced.
Since then, I had to add another change event to get fired, but here's my code for clarity.

preSelect2(
    getUrl: string,
    ngSelect2Id: string,
    document: Document
  ): Observable<any> {
    return this.http
      .get<any>(getUrl, {
        headers: new HttpHeaders().append('Content-Type', 'application/json'),
      })
      .pipe(
        tap((res) => { 
/*my server simply returns a json of { text: string; id: string; }, the id is set as the actual 
value for the underlying option, and the text is used for what the user sees, so what 
the select2 element shows as the value*/
          if (res) {
            const select = document
              .getElementById(ngSelect2Id)
              ?.querySelector('select');
            if (select != null) {
              select.textContent = '';
              const option = document.createElement('option');
              option.innerText = res.text;
              option.setAttribute('value', res.id);
              option.setAttribute('selected', 'selected');
              select.appendChild(option);
              select.dispatchEvent(new Event('change'));
              select.dispatchEvent(
                new CustomEvent('select2:select', {
                  detail: { data: res },
                })
              );
            } else {
              console.error('Select2 element not found. Cant preselect value.');
            }
          }
        })
      );
  }

Here's how you call it:

this.preSelect2(
                  API_URL + 'Get?id=' + this.myModel.id, // I use simple GET requests on the server for select2 selection
                  'myNgSelect2Id', // the id you give to the select, eg.: <ng-select2 id="myNgSelect2Id"></ng-select2> 
                  document // built-in property of all @Component in angular
                ).subscribe((success) => /* do something*/);

from ng-select2.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.