Ionic 4: Event handlers lost in hidden containers


#1

I have two DIV elements on my data gathering form. The first one provides a question and six opinion buttons with an event handler. A click will temporarily hide the first form and reveal a second one (the second DIV) which has three buttons. After the user presses any of the buttons the data is saved and the first div is revealed with a fresh question. This sounds simple but it only works for the first question.

When the first DIV is hidden and shown (by an *ngIf rule) all the buttons lose their event handlers and from the second question on the buttons in the first div will not fire any events. Is this ‘per design’ or could it be a bug? There being no events for ngIf-unhiding/rendering recreating the handlers must be done using timeout() which is neither reliable nor fast.

We have found hiding/showing containers the most convenient way because a reseach sometimes has 500+ questions and switching must be very fast without any fancy transitions. The only reliable way we have been able to do it in Ionic 4 is by using a ModalController which seems to retain the event handlers. We have run these surveys for years using HTML5 and responsive CSS but would like to test them as PWAs.

I admit I might have missed something, having only used Ionic V3 for one application so far.


#2

The way you say “event handlers” and “run for years” suggests to me that you’re manually interacting with the DOM. That’s generally contraindicated in Ionic apps, where one would typically use Angular instead.

Perhaps if you can post some code, somebody could suggest how it could be Angularized.


#3

(I thought) I was absolutely not doing any manual DOM handling. It was Angular *ngIf with variables the way we did with my Ionic3 app for another customer.

However, writing a dummy app seemed to show that the handlers added using AddEventHandler() will be lost and are very difficult to get added from the component code due to the asyncronic way Angular works. The Angular-added ones did stay there. So in that sense you are right about DOM handling. I assumed adding handlers would not give any troubles but…

Well, we will have to rethink the way produce the two forms and let Angular do even more of the job.

After reading the documentation I understood that ngIf really renders the section each time its variable value is changed. Thanks for kicking my butt :slight_smile:


#4

If you haven’t already read it, I would start here.


#5

Done that but I was living in the false assumption that one could add event handling and do some other tasks from Typescript. This is what one gets from using template for 30 years and starting to use a framework which resembles templates but is actually much more. Lessons learned:)