4

I want to fade out an element's child, by animating its opacity. It's working fine, but at the end of the animation, the child's style is reverted back to it's original state (opacity un-set).

How can this be prevented / how can I tell Angular to leave the style in the target state once the animation has completed?

Here's my code:

@Component({
  selector: 'app-playground',
  template: `
  <div [@simpleStateTransition]="simpleState">
    {{ simpleState }}
    <div class="fadeout">fade this child out!</div>
  </div>

  <button (click)="toggleSimpleState()">toggle simple state</button>
  `,
  animations: [
    trigger('simpleStateTransition', [
      transition('initial => extended', group([
        query('.fadeout', animate('300ms', style({'opacity': '0'})))
      ])),
    ])
  ]
})
export class PlaygroundComponent {

  simpleState = 'initial'

  constructor() { }

  toggleSimpleState() {
    this.simpleState = this.simpleState === 'initial' ? 'extended' : 'initial'
  }
}
Stefan Falk
  • 23,898
  • 50
  • 191
  • 378
Hoff
  • 38,776
  • 17
  • 74
  • 99
  • I dont have much idea on animation but you can try ngAfterViewInit as that is the sage when view render complated. just an idea – Aniruddha Das Oct 20 '17 at 15:31

1 Answers1

3

I found a solution, it's actually much easier than I thought. We don't need to get into the 'query for children and kick off their animation' business at all.

Simply create 2 separate animations, and trigger them from the same expression. Having separate triggers allows us to define start and end styles that persist after the animation is done.

Here is some sample code:

@Component({
  selector: 'app-component',
  templateUrl: './your.component.html',
  animations: [
    trigger('parentAnimation', [
      state('expanded', style(styles.backgroundExtended)),
      state('compact',  style(styles.backgroundCompact)),
      transition('expanded <=> compact', animate(timings.background))
    ]),
    trigger('childAnimation', [
      state('expanded', style(styles.hideExtended)),
      state('compact',  style(styles.hideCompact)),
      transition('expanded <=> compact', animate(timings.background))
    ])
  ]
})

<div [@parentAnimation]="visualState">
    <h1>Hello from parent</h1>
    <div [@childAnimation]="visulaState">
        A Child! 
    </div>
    <div [@childAnimation]="visulaState">
        Another Child! 
    </div>
</div>

To me this is much nice / cleaner / easier solution. Please leave a comment if you see any drawbacks.

Stefan Falk
  • 23,898
  • 50
  • 191
  • 378
Hoff
  • 38,776
  • 17
  • 74
  • 99