Now, let’s move on to closing the snack bar. First, we need to add the closing animation.

Listen for the closing click event and apply the leaving animation to the snack bar element.

In this stage, we’ll see the leaving animation, but the component will still be visible. The key point here is to wait for the animation to end and then call the componentRef.destroy() method and remove the DOM element from the body.

To achieve this, we can use the browser animationend event — the animationend event occurs when a CSS animation is completed.

One of the properties of the animationend event is the name of the current animation. We can check to see if the current animation is the snackbarOut animation. If it is, we can emit the afterClose event.

Now, in the open() method, we can subscribe to the afterClose event and destroy the component, but only after the animation ends.

We can also take it further, change it to be auto dismissible and accept the animation duration from the consumer.