Introduction

This article is an adaptation of this excellent article in the Angular context. The original article achieves the visual effects with the use of CSS Variables. Since every browser doesn’t yet support them, we will remake this effect with the use of Angular built-ins such as @HostListener and ngStyle .

The Setup

We start off by creating the button component. The gradient is positioned absolutely within the host element. We set the position to relative on the content span, to make sure it’s displayed above the gradient.

Track The Mouse Movement

First, we need a way to track the mouse movement within the button component. We want to achieve the following behavior:

Show the gradient when we mouse into the button. Hide the gradient when we mouse out of the button. Make the gradient follow the cursor.

As you can see, we use declarative @HostListener to react to mouse events.

The mouseenter and mouseleave events change the visibility of the gradient, and the mousemove event is used to track the mouse position within the button element.

Calculate The Gradient Size

Since buttons come in different forms and sizes, we want to vary the gradient size, depending on the context it’s displayed in. We size the gradient based on the host element’s width.

If you anticipate resizing the button after it is rendered, consider moving to calculate the gradient radius to the ngDoCheck lifecycle hook. For most applications, setting it once in the ngAfterViewInit should suffice.

Dynamic Gradient Size

Style The Gradient