【问题标题】:Prevent angular animation when switching route切换路线时防止角动画
【发布时间】:2021-01-26 03:05:37
【问题描述】:

我有一个对象数组,我想在删除时设置动画:

<div [@arrayAnim]="motives.length">
    <div class="motive" *ngFor="let motive of motives"><div>
    <div class="motive-name">{{motive.name}}</div>
    ...

    <mat-icon class="delete-icon" (click)="deleteMotive(motive)">delete</mat-icon>
</div>

在我的组件动画中,我构建了一个数组动画触发器,如下所示:

@Component({
  selector: 'app-motives',
  templateUrl: './motives.component.html',
  styleUrls: ['./motives.component.scss'],
  animations: [
    trigger('arrayAnim', [
      transition('* => *', [
        query(':leave', stagger('300ms', [
          animate('500ms ease-out', keyframes([
            style({opacity: 1, transform: 'scale(1.1)', offset:0}),
            style({opacity: .5, transform: 'scale(.5)', offset: .3}),
            style({opacity: 0, transform: 'scale(0)', offset:1})
          ]) )
        ]), {optional: true})
      ])
    ])
  ]
})

当 siwtching 路由时,即使我没有删除数组的任何元素,也会触发转换。我不明白这种行为。为什么路由改变时会触发动画?

我在 stackblitz 上创建了一个最小示例:

https://stackblitz.com/edit/angular-ivy-wdyzlh?file=src/app/prices/prices.component.ts

从价格到产品到价格路径的切换将触发意外行为。删除价格将按预期工作。

更新

正如评论中所建议的,我可以将 arrayAnim div 包装在另一个会禁用基于组件变量的动画的 div 中。

<div [@.disabled]="noAnimation">
    <div [@arrayAnim]="motives.length" (@arrayAnim.done)="onAnimationDone()">
        <div class="motive" *ngFor="let motive of motives"><div>
        <div class="motive-name">{{motive.name}}</div>
        ...

        <mat-icon class="delete-icon" (click)="deleteMotive(motive)">delete</mat-icon>
    </div>
</div>

在我的组件中,我有一个 noAnimation 属性,一旦删除完成,该属性就会切换为 true。触发 deleteMotive() 方法时,no animation 属性将设置为 false

【问题讨论】:

    标签: angular


    【解决方案1】:

    试试这个:

    <div [@.disabled]="noAnimation">
      <div [@arrayAnim]="priceArray.length">
        <div *ngFor="let p of priceArray" class="price" (click)="deletePrice(p)">
          Regular: {{p.regular}}
          Discounted: {{p.discounted}}
        </div>
      </div>
    </div>
    <p>Click on a price to delete it</p>
    

    组件.ts:

      noAnimation = true;
    
      deletePrice(p) {
        this.noAnimation = false;
        this.priceArray = this.priceArray.filter(price => price != p);
    
        //After animiation was executed - disable it again
    
        setTimeout(()=> {
          this.noAnimation = true;
        }, 500);
      }
    

    【讨论】:

    • 你还在用它来制作 whoe list 的动画吗?我添加了一个 stackblitz 示例,我在其中复制了该行为。
    • 对不起,那是我的错。我更新了我的答案。知道我应该工作。
    • 谢谢,它可以工作,但是我不太喜欢 setTimeout,它似乎有点 hacky。也许还有另一种方式。另外我想了解是什么导致了混乱。我觉得路由器插座是问题所在。
    • 模板中似乎有更好的方法来触发动画完成。 (@arrayAnim.done)。我会更新我的问题。仍然没有确认答案,因为我需要了解为什么我确实需要使用禁用动画。
    • 问题,为什么你的动画在路由期间也被触发是因为 transition('* => *') - 请参阅此处了解更多信息:angular.io/guide/transition-and-triggers
    猜你喜欢
    • 1970-01-01
    • 2016-05-13
    • 2017-09-07
    • 2014-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多