首页 > 解决方案 > 为什么动画回调会扰乱我组件的生命周期?

问题描述

我做了一个简单的翻牌组件:

card.component.html:

<div class="card"
[@rotatedState]="state"
[@rotatedState.start]="rotateStart()"
[@rotatedState.done]="rotateDone()"
>
<div class="front">
    <h2 class="title">Lorem.</h2>
    <ul class="tags" *ngIf="tags != ''">
        <li class="tag" *ngFor="let tag of tags.split(' ')">{{tag}}</li>
    </ul>
    <p class="description">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consectetur, porro.</p>
</div>
<div class="back">
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Veritatis, error.
</div>

card.component.ts:

import { AfterViewChecked, Component, HostListener, Input, OnInit } from '@angular/core';
import {trigger, state, style, animate, transition} from '@angular/animations';

@Component({
    selector: 'app-card',
    templateUrl: './card.component.html',
    styleUrls: ['./card.component.scss'],
    animations: [
       trigger('rotatedState', [
       state('default', style({ transform: 'rotateY(0)' })),
       state('rotated', style({ transform: 'rotateY(-180deg)' })),
       transition('rotated => default', animate('400ms 100ms ease-out')),
       transition('default => rotated', animate('400ms 100ms ease-in'))
       ])
    ],
})

export class CardComponent implements OnInit, AfterViewChecked {
  @Input() title: string = '';
  @Input() tags: string = '';

  state: string = 'default';
  isTransitioning: boolean = false;

  constructor() {
  }

  ngOnInit(): void {
  }

  ngAfterViewChecked(): void {
    console.log('View Checked!');
  }

  @HostListener('mouseenter')
  @HostListener('mouseleave')
  rotate(): void {
      if (!this.isTransitioning) {
          this.state = (this.state === 'default' ? 'rotated' : 'default');
      }
  }

  rotateStart(): void {
      this.isTransitioning = true;
  }

  rotateDone(): void {
      this.isTransitioning = false;
  }
}

我想在动画已经运行时防止旋转。我不明白的是:当模板中存在我的动画的回调函数绑定时,我的组件在 viewcheck 之前被卡在它的生命周期中的某个地方,因此标签在第一个动画触发之前在组件上不可见,即使我以这种方式使用组件:

<app-card tags="tag1 tag2"></app-card>

如果我从模板( [@rotatedState.start]="rotateStart()" [@rotatedState.done]="rotateDone()" )中删除回调的绑定,那么它工作正常。有人可以启发我这种行为吗?我搜索了它,但没有找到任何有用的信息。

标签: javascriptangularng-animate

解决方案


推荐阅读