Search code examples
angularanimationangular-animations

Angular 17, fade animation for when value changes, not working


I can't seem to get this to work.

In child component:

animations: [
        trigger('simpleFadeAnimation', [
            transition('*=>*', [
                style({opacity: 0}),
                animate(600)
            ])
        ])
    ]


 <p [@simpleFade]>
    {{ fieldValue() ? fieldValue() : "-" }}
  </p>

In parent:

Here the input value is conditional, and depends on toggling a boolean in the parent

<app-child
  [fieldValue]="booleanVariable ?? false) ? field.value : field.valueAlt"/>

I can't get the text field in the child to fade when the value is toggled. It just keeps snapping to the new value. Any ideas where I may be going wrong?

Thanks in advance!

UPDATE

My final solution:


Solution

  • The trigger name has to match the html attribute that was the problem!

    We also need to use a combination of opacity 0 -> 1 -> 0 for each word change, we can use transition to define an animation sequence which will do this for us!

    child ts

    import {
      animate,
      sequence,
      state,
      style,
      transition,
      trigger,
    } from '@angular/animations';
    import { Component, input } from '@angular/core';
    
    @Component({
      selector: 'app-child',
      standalone: true,
      imports: [],
      templateUrl: './child.component.html',
      styleUrl: './child.component.css',
      animations: [
        trigger('showOrHide', [
          state(
            'true',
            style({
              opacity: 0,
            })
          ),
          state(
            'false',
            style({
              opacity: 0,
            })
          ),
          transition('true => false', [
            style({ opacity: 0 }),
            animate('.75s ease-in'),
            style({ opacity: 1 }),
            animate('.75s ease-out'),
          ]),
          transition('false => true', [
            style({ opacity: 0 }),
            animate('.75s ease'),
            style({ opacity: 1 }),
            animate('.75s ease'),
          ]),
        ]),
      ],
    })
    export class ChildComponent {
      fieldValue = input();
      toggle = input();
    }
    

    child html

    <p [@showOrHide]="toggle()">
      {{ fieldValue() ? fieldValue() : '-' }}
    </p>
    

    Stackblitz Demo