Can we implement advance transitions/animations wi

2019-05-21 08:23发布

问题:

I need to implement animations only with angular 4. Below is a sample advance animation that would like to implement. Tried and I couldn't write parallel div animations with angular4. Because with parallel div animations this could achieve via CSS also I believe with angular4 also. So if anyone knows how to write please provide any hint or code.

Note: I need to include it into router transition just as the example.

Animation Sample

回答1:

A way to do this is to use the transition alias :enter to trigger the animation when the component loads, and then you can use the animations states, so when you click on a link, you toggle the state to trigger the animation, and once the animation is done, you can finally navigate to the page you want.

To do something once the animation is done, use this : (@animation.done)="onDone(event)" in the template.

I used two <div>, one at the top of the page and another one at the bottom. When the animation is triggered, their height go from 0px to half of the window (50vh).

Here is a StackBlitz example I made for this.

component.html

<div [@extend]="state" (@extend.done)="onDone(event)" class="animation-div div-top"></div>

<div class="main-div">
    <a (click)="goTo()">Link 1</a>
    <!-- page content -->
</div>
<div [@extend]="state" class="animation-div div-bottom"></div>

component.ts

import { Component, OnInit } from '@angular/core';
import { extend } from '../animations';
import { Router } from '@angular/router';

@Component({
  selector: 'home',
  templateUrl: './home.component.html',
  animations: [extend],
  styleUrls: ['../app.component.css']
})
export class HomeComponent implements OnInit {

  state = 'out';
  constructor(private router: Router) { }

  ngOnInit() {
    this.state = 'out';
  }

  onDone($event) {
    if (this.state === 'in') {
      this.router.navigate(['shop']);
    }
  }

  goTo() {
    this.state = 'in';
  }
}

animations.ts

import { animate, state, style, transition, trigger } from '@angular/core';

export const transitionTime = '1.5s';

export const extend =
  trigger('extend', [
    state('in', style({ height: '50vh' })),
    state('out', style({ height: '0px' })),
    transition(':enter', [
      style({
        height: '50vh'
      }),
      animate(transitionTime, style({
        height: '0px'
      }))
    ]),
    transition('* => *', [
      animate(transitionTime)
    ])
  ]);

component.css

.animation-div {
  height: 0px;
  background-color: gray;
  width: 100%;
}

.div-top {
  position: absolute;
  top: 0px;
}
.div-bottom {
  position: absolute;
  bottom: 0px;
}

.main-div {
  position: absolute;
  top: 50px;
  z-index: -1;
}