Animate child element in Angular 2 animation

1.5k Views Asked by At

Here is my template

<div class="navbarTitle" [@myTrigger]='state' (mouseenter)='animateUnderscore()'>Hello<span class="titleUnderscore">_</span>Everyone</div>

As you can see there is span element within the div containing an underscore between Hello and Everyone text.

The method within my component which toggles the color of the text (animation is done using angular animations defined within the component's decorator)

//** Within component
titleIsBlue: boolean = false;

//method which changes the color of the underscore on hover
animateUnderscore = () => {
    if (this.titleIsBlue) {
        state = 'black';
        titleIsBlue = false;
    } else {
        titleIsBlue = true;
        state = 'blue';
    }

}
//** Within Component

How can I get hold of the span element containing the underscore so that I can change it's color?

I don't wanna use jQuery or Angular2's elementRef.

1

There are 1 best solutions below

1
On BEST ANSWER

Depending on what you what property you want to change you can use for example the [style.color] binding to change the text colour:

<div class="navbarTitle" [@myTrigger]="state" (mouseenter)="animateUnderscore()">
   Hello
   <span class="titleUnderscore" [style.color]="underscoreColor">_</span>
   Everyone
</div>

In your class you have to define this property then:

titleIsBlue: boolean = false;
underscoreColor: string = '#000';    

//method which changes the color of the underscore on hover
animateUnderscore = () => {
    if (this.titleIsBlue) {
        this.state = 'black';
        this.titleIsBlue = false;
        this.underscoreColor = '#F00';
    } else {
        this.titleIsBlue = true;
        this.state = 'blue';
        this.underscoreColor = '#00F';
    }
}

Little side note, please use double quote inside templates to prevent parsing erros :)