Hi everyone,
I’m using Angular 5 and I have made an Angular component called Select2Dropdown for select2 plugin.
My version of Select2 is 4.0.3.
Currently as far as I know, select2 uses only local data for searching.
My goal is to customize my Select2Dropdown to use remote search as well.
Currently, I already manage to do that but it’s not good as it should.
Problems:
-
The first problem is that search events (keypress, keyup, or else) are not triggering if select2 has no loaded data (options). I was able to ‘trick’ that by inserting hidden option to my select2.
How can I change this to be able to trigger search with no data available? -
Second problem is that I know only for matcher callback method that I can replace with my custom match function that will handle custom search matching and I made that.
This function looks something like this:searchCustomers(params, data) { // If there are no search terms, return data if ($.trim(params.term) === '') { return data; } if (this.customerSearchParams === params.term) { return data; } else { this.customerSearchParams = params.term; this.customers = []; this.customerService.getCustomers() .subscribe( // Successful responses call the first callback. customers => { this.customers = customers; $('#mySelect2').select2('close'); $('#mySelect2').select2('open'); // Get the search box within the dropdown or the selection const $search = $('#mySelect2').data('select2').dropdown.$search || $('#mySelect2').data('select2').selection.$search; $search.val(params.term); } }); } return data; }
So, on each search keypress my callback searchCustomers() is called and I’m fetching my customers from database. This is asynchronous method and after success my select2 is loaded with new data and it shows new data in the search results but if I select any of that data it just selects empty.
I manage to ‘trick’ select2 by closing and reopening select2 dropdown and replacing search text with previous value. That happens so fast that user doesn’t notice anything.
But the problem is that each keystroke triggers fetching from database and on success it reopens select2 so if I started to write some word in search it stops and continue and it swallowed me a letter.
So, if I write slowly everything works but that is not what it should be.
I was wondering how can I change search trigger event to be triggered on pressing enter key?
So to summarize:
- How to trigger search if no data?
- How to replace search trigger from any keypress to pressing enter key only?
- Any other suggestion will be very welcome!!
Best regards,
Josip