Angular 4 animate parent and child components at the same time

你说的曾经没有我的故事 提交于 2019-12-04 07:53:08

I'd like to say that using callbacks is the best way to handle this for future code, but if you just need to get this to work the trick is to use OnChanges, SimpleChanges, and a setTimeout().

Working Plunker to show how it works, as well as the inner div main changes in code:

imports

import {Component, Input, OnChanges, SimpleChanges} from '@angular/core'

template

  template: `
    <div [@stateInner]="localChange">
      <h2>Hello</h2>
    </div>

class export

  localChange = 'narrow';

  ngOnChanges( changes: SimpleChanges ) {
    console.log(changes)
    setTimeout( () => this.localChange = changes.stateInner.currentValue, 500);
  }

You can run parent and child animations at the same time without events and timeouts, animateChild() can help us. Here is the parent animations description:

animations: [
    trigger('state', [
        state('narrow', style({
            width: '100px'
        })),
        state('wide', style({
            width: '400px'
        })),
        transition('narrow => wide', [
            style({
                width: '100px'
            }),
            group([
                animate('500ms', style({
                    width: '400px'
                })),
                query('@stateInner', [
                    animateChild()
                ])
            ])
        ]),
        transition('wide => narrow', [
            style({
                width: '400px'
            }),
            group([
                animate('500ms', style({
                    width: '100px'
                })),
                query('@stateInner', [
                    animateChild()
                ])
            ])
        ])
    ])
]

group() - runs multiple animations in parallel, here is an example from the documentation

query() - finds child animations

animateChild() - executes child animations

The drawback of this solution, as you may notice, I described forward and backward parent transitions and styles separately, otherwise the parent state isn't animated correctly for some reason. Here is my question about the problem.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!