0

如何在 Angular2 中删除 dom 元素时触发动画?

import { Component, Input, Output, EventEmitter } from '@angular/core';
import { FormGroup, FormControl, Validators } from "@angular/forms";

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

import { ServerService } from './server.service';

@Component({
  selector: 'fc-server',
  templateUrl: './server.component.html',
  animations: [
  trigger('flyInFlyOut', [
    state('*', style({transform: 'translateX(0)', opacity: 1})),
    transition('void => *', [
      style({transform: 'translateX(-100%)', opacity: 0}),
      animate('400ms ease')
    ]),
    transition('* => void', [
      style({transform: 'translateX(-100%)'}),
      animate('400ms ease')
    ])
  ])
  ]
})
export class Server {

  @Input() serverInstance;

  serverForm;

  constructor(
    private serverService: ServerService) {}

  ngOnInit() {
    this.serverForm = new FormGroup({
      serverName: new FormControl('', Validators.required),
      serverPort: new FormControl('', Validators.required),
      serverIp: new FormControl('', Validators.required),
    });
  }


  @Output() remove = new EventEmitter();

  onRemove() {
    this.serverService.remove(this.serverInstance);
  }

  onSubmit(serverInstance) {
    this.serverService.add(serverInstance);
  }
}

一切正常,从列表中删除项目,将项目添加到列表中,动画...除了删除项目时,列表项目被删除而没有动画。有什么见解吗?

这似乎是 Angular2 反复出现的问题,但据我所见,没有人真正有好的解决方案。

例如这篇文章:https ://www.bennadel.com/blog/3140-using-changedetection-with-animation-to-setup-dynamic-void-transitions-in-angular-2-rc-6.htm

4

2 回答 2

1

你也需要定义你的state结束void

state('void', style({transform: 'translateX(100%)', opacity: 0}))

然后删除过渡中的style({transform: 'translateX(-100%)'}),行。* => void

或者,在我看来,我会把它写成更容易理解的形式:

trigger('flyInFlyOut', [
  transition(':enter', [
    // the element receives this style immediately and then animates to the 
    // next style which is the `style({ transform: 'translateX(0)', opacity: 1 })`
    style({ transform: 'translateX(-100%)', opacity: 0 }),
    animate('300ms', style({ transform: 'translateX(0)', opacity: 1 })),
  ]),
  transition(':leave', [
    style({ transform: 'translateX(0)', opacity: 1 }),
    animate('200ms', style({ transform: 'translateX(100%)', opacity: 0 })),
  ]),
]);

:leave和分别是和的:enter简写。* => voidvoid => *

于 2017-06-12T04:25:56.163 回答
0

我不知道您是否仍需要解决方案,但您可以将动画设置为 true,并且为了更简洁的代码,您可以定义 void 状态的样式而不是 *(默认),角度足够聪明,可以知道最终的样式应该看起来像,例如:

@Component({
  selector: 'fc-server',
  templateUrl: './server.component.html',
  animations: [
  trigger('flyInFlyOut', [
    state('void', style({transform: 'translateX(-100%)', opacity: 0})),
    transition('void => *', [
      animate('400ms ease')
    ]),
    transition('* => void', [
      animate('400ms ease')
    ])
  ])
  ],
  host: {
    '[@flyInFlyOut]': 'true'
  }
})

此外,如果您想为 (void => ) 和 ( => void) 转换使用别名,它们分别是 (:enter) 和 (:leave) ,如另一个答案中所述。

我遇到了完全相同的问题并找到了这个解决方案。希望能帮助到你。:)

于 2018-02-14T21:41:18.293 回答