Creat custom reusable Alert (or Modal) component

I have an alert that has some startup and other logic attached which I would like to reuse in multiple places inside my app.

My current solution which I do not like is that I have a component which on construction creates and presents the alert.
so when I want the alert to show up I have to push my new component onto the stack which then results in the alert showing up. On alert cancel or action I pop my new component off of the stack and it returns to the previous view.

The problem is that a white screen appears before the alert and then disappears, so the alert isn’t really being shown on top of the correct view.

Is there a better way to do this?

Can you have your reusable code spit out an AlertOptions which can then be passed to the AlertController every time you wish to pop the alert? That way you are down to two lines in each place the alert is generated:

let alert = this.alerts.create(this.customAlerts.makeAlertOptions());

1 Like

That might be possible, but another solution was suggested here which I’ve decided to go with

It’s a service which creates and presents the alert instead of using a component to do it.

I hope you have luck with that. I have personally had more success when I follow the rule of “don’t interact with the view layer from services”. For one thing, it greatly reduces the incidence of accidental circular dependencies.

That makes sense.
I’m curious where this rule is coming from? Something you’ve seen in Ionic/angular documentation or just an overarching rule of thumb when it comes to building applications?


I suppose more of the latter. If services stick to exchanging and providing data, I feel it reduces the coupling of entities. Perhaps this is not analogous to your situation, but one common topic I’ve seen here several times (and tried myself to implement before running into various problems and deciding to abandon the idea) is “a subclass of Http that handles all my authorization and pops alerts when there are network errors”. There’s just too much going on in there, and it makes the class monolithic, inflexible, and brittle. Eventually you will run into a situation where popping the alert isn’t desirable, and then you need to add a bunch of options that you were trying to avoid in the first place.