簡體   English   中英

在表達式值更改時添加動畫 - Angular 5

[英]Add animation when expression value changes - Angular 5

我在一個名為“pointsBalance”的頁面上有一個顯示數值的表達式。 它連接到一個observable ,當 pointsBalance 值上升時,我想將顏色更改為綠色,然后返回其原始顏色,如果值下降,則為紅色。 我以為我可以使用Angular 5 的新動畫別名:increment 和 :decrement但我一直遇到問題。

顯示積分余額的 HTML:

<div [@valueAnimation]="pointsBalance">{{ pointsBalance }}</div> 

設置動畫和可觀察的 pointsBalance 的代碼:

import { Component, OnInit, Input } from '@angular/core';
import { trigger, style, transition, animate, keyframes, query, 
    stagger, state, group } from '@angular/animations';
import { CompetitionsService } from "../../../shared/index";
@Component({
  selector: 'points',
  templateUrl: './...html',

  animations: [
    trigger('valueAnimation', [
      transition(':increment', group([
        query(':enter', [
          style({ color: 'green', fontSize: '50px' }),
          animate('0.8s ease-out', style('*'))
        ])
      ])),
      transition(':decrement', group([
        query(':enter', [
          style({ color: 'red', fontSize: '50px' }),
          animate('0.8s ease-out', style('*'))
        ])
      ]))
    ])
  ]
})
export class CompetitionDetailsComponent implements OnInit {

  pointsBalance: number;

  constructor(private competitionsService: CompetitionsService, ) { }

  ngOnInit() {

    this.competitionsService.updatePointsBalance$.subscribe(
      (pointsBalance) => {
        this.pointsBalance = pointsBalance;
      }
    )
  }
}

當 pointsBalance 值更改時,我收到此控制台錯誤:

錯誤錯誤:由於以下觸發轉換失敗,無法處理動畫@valueAnimation 因以下原因而失敗:

  • query(":enter")返回零個元素。 (如果您希望允許這樣做query(":enter", { optional: true })請使用query(":enter", { optional: true }) 。)

有誰知道我為什么會收到這個錯誤? 還是有另一種方法來實現這一目標? 謝謝。

:enter動畫只會為新創建的元素設置動畫。 您的“hacky”解決方法有效,因為它會在值發生變化時強制重新創建內部跨度。 我認為您想要的是刪除:enter查詢。 您希望在數字進入/遞減時進行動畫處理,並且您的動畫與添加的元素無關。

我從這里這里找到了一個修復程序。

<div [@valueAnimation]="pointsBalance"><span *ngFor="let pointsBalance of [ pointsBalance ]">{{ pointsBalance }}</span></div>

雖然感覺有點hacky。

正如本傑明·金德爾Benjamin Kindle)所說,我只是按照它的樣子粘貼代碼,我試過了,它奏效了:

animations: [
    trigger('valueAnimation', [
      transition(':increment', [
          style({ color: 'green', fontSize: '50px' }),
          animate('0.8s ease-out', style('*'))
        ]
      ),
      transition(':decrement', [
          style({ color: 'red', fontSize: '50px' }),
          animate('0.8s ease-out', style('*'))
        ]
      )
    ])
  ]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM