css - 在 Angular 4 中动画化图像交换(在 AngularJS 中是 ng-animate-swap)

标签 css angular animation angular-animations web-animations

我想在 Angular 4 应用程序中制作图像交换动画。当 Controller 替换 img src 属性时,旧图像应该消失,新图像出现。

在 AngularJS 中,这可以通过使用 ng-animate-swap 更改不透明度来实现。但是,Angular 4 似乎不支持动画交换。如果没有交换触发器,如何实现这一点?

我已经尝试为 src 属性添加从 void 到 * 和返回的转换,但这没有按预期工作。第一张图片有动画,后面的交换没有动画。

@Component({
  selector: 'app-play-card',
  template: '<div (click)="loadImg()"><img [@fade]="imgsrc" src="{{ imgsrc }}" /></div>',
  styleUrls: ['./play-card.component.css'],
  animations: [
    trigger('fade', [
      transition('void => *', [
        style({opacity: 0.1}),
        animate(5000, style({opacity: 1}))
      ]),
      transition('* => void', [
        style({opacity: 0.9}),
        animate(5000, style({opacity: 0}))
      ])
    ])
  ]
})

最佳答案

下面是我如何使用 Angular 动画状态:

animations.ts

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

export const fade = [
  trigger('fade', [
    state('in', style({ 'opacity': '1' })),
    state('out', style({ 'opacity': '0' })),
    transition('* <=> *', [
      animate(1000)
    ])
  ])
];

app.component.html

<img [@fade]="state" (@fade.done)="onDone($event)" [src]="imageSource" width="500" (click)="onClick()" />

我使用了 (@fade.done),这是 Angular 动画的一个特性,它允许您在动画完成后调用一个方法。

在这里,当第一个动画淡出到不透明度为 0 时,我更改了图像路径,并更改了动画状态,再次淡入淡出并将不透明度值恢复为 1。

app.component.ts

export class AppComponent implements OnInit {
  choice = 2;
  state = 'in';
  counter = 0;
  enableAnimation = false;
  imageSource = '';
  imgSrc1 = 'firstPath';
  imgSrc2 = 'secondPath';

  ngOnInit() {
    this.imageSource = this.imgSrc1;
  }

  onClick() {
    this.enableAnimation = true;
    this.counter = 0;
    this.toggleState();
  }

  toggleImg() {
    if (this.choice === 1) {
      this.imageSource = this.imgSrc1;
      this.choice = 2;
    } else {
      this.imageSource = this.imgSrc2;
      this.choice = 1;
    }
  }

  onDone($event) {
    if (this.enableAnimation) {
      if (this.counter === 1) {
        this.toggleImg();
      }
      this.toggleState();
    }
  }

  toggleState() {
    if (this.counter < 2) {
      this.state = this.state === 'in' ? 'out' : 'in';
      this.counter++;
    }
  }
}

虽然对于一个小动画来说,这显然是很多代码。

这是我为此制作的 StackBlitz 示例:https://stackblitz.com/edit/angular-anim-fade-img

关于css - 在 Angular 4 中动画化图像交换(在 AngularJS 中是 ng-animate-swap),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47538186/

相关文章:

css - 如何隐藏一侧阴影效果?

javascript - Angular4中三种类型的数据绑定(bind)指令 : [val] , [(val)] , (val) 有什么区别

javascript - angular2-systemJS 路径不起作用

angular - 在 Angular 延迟加载中找不到模块

javascript - 在 AngularJS/ngAnimate 中显示/隐藏时向左/向右滑动动画

javascript - 使用 JS 遍历 SVG

html - 我的 DIV 元素怎么了?

jquery - 阻止 div 动画在未来被触发

animation - 没有补间的 CSS3 Sprite 动画

html - Bootstrap 导航栏按钮未显示