Getting Select2 and Livewire Working without wire:ignore and validation without getting disabled

Hi, eveyone.
I was facing a lot issues to get Livewire working with select2 ,i tried most of the workaroung in this forum.

The first things was that if i use laravel validation select2 was getting disabled after any validation message, it’s turn out that wire:ignore was causing the issues.

The second if you remove wire:ignore then select2 stop working, everything get disabled.

The third was that if i set the property value this way @this.set(‘foo’,‘bar’) when i click submit, if there was any validation error then the property lost the value and select2 get empty.

So these are the things that i did to get it working.
I’m not pushing the script to the stack, cause i did it, didn’t work etheir, all the javascript is inside the component.

First remove wire:ignore from the div that contains the element.

Second create a function that is available in the global scope and initialize select :
$(document).ready(function () {
window.initTicketTypesDrop=()=>{
$(’#ticketType’).select2({
placeholder: “Select your option”,
allowClear: true,
});
}
initTicketTypesDrop();

//Here i set select2 values to localStore and set it to the public property ticketstypes

   $('#ticketType').on('change', function (e) {
             localStorage.setItem('ticketstypes',$(this).val());
             @this.set('ticketstypes',JSON.stringify($(this).val()));
        });

});

then in the component backend:
Each time there is dom update, this going to fire an event, that i listen in the client side and initialize the select2
public function hydrate(){
$this->emit(‘select2’);
}

//Client side: here i Listen the event and initialize the select2
window.livewire.on(‘select2’,()=>{
initTicketTypesDrop();
});

//Then i set the select2 value from localStorare that is lost during any request from the component
document.addEventListener(“livewire:load”, function(event) {
window.livewire.hook(‘afterDomUpdate’, () => {
if(localStorage.getItem(‘ticketstypes’))
{
$(’#ticketType’).val(localStorage.getItem(‘ticketstypes’).split(’,’));
}

    });
});

Why i dont initialize the select2 from the livewire hook ‘AfterDomUpdate’?
Cause when this event execute the dropdown the select2 library is not able to init, so i used the window.livewire.on that is the last things to execute when request is completed and select2 works without any problems.
Select2-Working
This can be use with multiples select2, instead id use a class.

This has helped a lot. Thanks.