Can we implement advance transitions/animations with angular 4?

ε祈祈猫儿з 提交于 2019-12-06 13:30:14

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