sweetalert2 / ngx-sweetalert2

Declarative, reactive, and template-driven SweetAlert2 integration for Angular
MIT License
660 stars 94 forks source link

Components inside a *swalPortal cannot be accessed through @ViewChild #180

Closed dodos90 closed 3 years ago

dodos90 commented 4 years ago

Hi everyone !

I'm having some troubles with a feature working in Angular 8 / Sweetalert 8 / NGX-Sweetalert 7, and that does not work anymore after upgrading to Angular 9 / Sweetalert 9 / NGX-Sweetalert 8.

Basically, I'm trying to access a custom component within a *swalPortal by using @ViewChild, but the component stays undefined.

My template (simplified, in order to focus on what's important) :

<swal
      [showLoaderOnConfirm]="true"
      [confirmButtonText]="'labels.YES' | translate"
      [preConfirm]="submit.bind(this)">

    <div *swalPortal>
        <mys-select-working-areas #selectWorkingAreasComponent></mys-select-working-areas>
    </div>
</swal>

The controller :

selectWorkingAreasComponent: SelectWorkingAreasComponent;
@ViewChild('selectWorkingAreasComponent') set setSelectWorkingAreasComponent(element) {
    if (element) {
        this.selectWorkingAreasComponent = element;
    }
}

submit() {
    this.selectWorkingAreasComponent.submit(); // "selectWorkingAreasComponent" is undefined here
}

Basically, the @ViewChild is not refreshed by Angular when the dialog is opened (and therefore, my selectWorkingAreasComponent is still undefined even though it now exists in the DOM)

A few things that I have noted while trying to fix this issue :

I have settled with the latter, but I would like to understand why this issue popped up.

Thanks a lot for your help !

toverux commented 3 years ago

Hi, I was not able to reproduce this with Angular 11. My ViewChild setter is called with the proper element when the modal is opened, then set to undefined when the modal is closed, and it continues to work if I keep opening and closing the modal.

I'd suggest you upgrade Angular and double check there's nothing interfering with your change detection. Please note that I've also checked that it works with OnPush change detection on my side.

Good luck!