javascript - :enter and :leave Angular animations 没有平滑过渡

标签 javascript angular angular-animations

我想要使用 Angular 动画实现平滑的滑入和滑出动画。我正在使用 ngSwitch 来显示/隐藏这些组件。传入的组件会在前一个组件消失之前将其向上推。我尝试过添加延迟,但这并不能解决问题。

app.component.html

<div class="container" [ngSwitch]="counter">
  <div @slideInOut *ngSwitchCase="1"></div>
  <div @slideInOut *ngSwitchCase="2"></div>
  <div @slideInOut *ngSwitchCase="3"></div>
  <div @slideInOut *ngSwitchCase="4"></div>
</div>

<button (click)="handleNext()">Next</button>

app.component.scss

.container {
  div {
    width: 100px;
    height: 100px;
    background: pink;
  }
}

app.component.ts

import { Component } from '@angular/core';
import { slideInOut } from './shared/animations';


@Component({
  selector: 'my-app',
  styleUrls: ['./app.component.scss'],
  animations: [ slideInOut ],
  templateUrl: './app.component.html',
})
export class AppComponent {
  readonly name: string = 'Angular';
  counter = 1;

  boxArr = [1, 2, 3, 4]

  handleNext(){
    if(this.counter <= this.boxArr.length){
      this.counter += 1
    } else {
      this.counter = 1
    }
  }
}

动画.ts

import { trigger, state, style, transition, animate, keyframes } from "@angular/animations";


export const slideInOut =  trigger('slideInOut', [
    transition(':enter', [
      style({transform: 'translateX(100%)'}),
      animate('200ms ease-in', style({transform: 'translateX(0%)'}))
    ]),
    transition(':leave', [
      animate('200ms ease-in', style({transform: 'translateX(-100%)'}))
    ])
])

演示:https://stackblitz.com/edit/angular-na1ath

最佳答案

问题在于:

1) 当您处理 display: block 时,无论是否还有剩余空间,元素都会占用整行宽度,因此您的幻灯片会分成两行

2) 如果我们通过添加 display: inline-block 来解决这个问题,我们就必须处理当有两个元素时它们比一个元素占用更多的空间。同时,translate 实际上并不移动您的元素,而只是移动它的可见部分(“物理”形状位于相同位置)

因此,通过幻灯片的绝对定位解决了这个问题

https://stackblitz.com/edit/angular-zciezz?file=src/app/app.component.scss

.container {
  position: relative;
  width: 100px;
  height: 100px;

  div {
    position: absolute;
    top: 0;
    left: 0;
    width: 100px;
    height: 100px;
    background: pink;
  }
}

关于javascript - :enter and :leave Angular animations 没有平滑过渡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58756640/

相关文章:

html - Angular 4 下拉菜单无法使用动画

angular - 动画 Angular2 中的参数

javascript - 在页面上循环多个视频并访问内部元素 - Javascript

javascript - 如何在 Azure Function 中使用 Azure 存储表?

javascript - 使用 Angular 2 Http 从 REST Web 服务获取数据

angular - 如何保护 Azure API 管理中的 API,然后通过 Angular (adal-angular5) 进行访问?

angular2组件过渡动画

javascript - (SystemJS)XHR错误@ angular/commobundles/common.umd.js/http未找到

javascript - 如何在 jstree 3 中为叶节点显示类似文件的图标

node.js - 如何在Live Server(Digital Ocean)中部署Angular App?