Search code examples
htmlangulartypescriptsass

Angular - Dynamic text gradient


I am attempting to dynamically change the gradient of some text in Angular (not the background but the text itself).

My current code is as follows:

home.component.html

<div class="name" [style.background]="gradient" 
    [style.-webkit-background-clip]="'text'"
    [style.background-clip]="'text'">Text Here</div>

home.component.sass

.name
    color: transparent
    font-family: Tahoma, sans-serif
    background: #FA8BFF
    background-clip: text
    -webkit-background-clip: text

home.component.ts

...
gradient : string = "linear-gradient(270deg, #FA8BFF 0%, #2BD2FF 42%, #2BFF88 90%)";

ngOnInit(): void {
  addEventListener("mousemove", (event) => {
    var angle = event.clientX + event.clientY;
    this.gradient = `linear-gradient(${angle}deg, #FA8BFF 0%, #2BD2FF 42%, #2BFF88 90%)`;
  })
}
...

This works as expected when the page is loaded, but the instant that I trigger the mousemove event, the text turns into a square for the rest of the time the page is active.

How do I properly apply a dynamic gradient to my Angular text?


Solution

  • Update Use (see the "text" before linear-gradient)

    gradient : string = "text linear-gradient(270deg, #FA8BFF 0%, #2BD2FF 42%, #2BFF88 90%)";
    
      addEventListener("mousemove", (event) => {
        var angle = this.mouseAngle(event.clientX, event.clientY);
        this.gradient = `text linear-gradient(${angle}deg, #FA8BFF 0%, #2BD2FF 42%, #2BFF88 90%)`
      })
    

    And

    <div class="name" [style.background]="gradient">Text Here</div> 
    
    The before code only works in FireFox

    Work in FireFox, Chrome and Edge (I don't check others) We need change background-image, not background

    .name{
        color: transparent;
        font-weight:800;
        font-size:16rem;
        font-family: Tahoma, sans-serif;
        background: #FA8BFF;
        background-clip: text;
        -webkit-background-clip: text
      }
    
    <div class="name" [style.background-image]="gradient">Text Here</div>