首页 > 解决方案 > 文本更改不起作用时的角度淡入/淡出

问题描述

我目前正在尝试在 Angular 中构建一个单词轮播。这个想法是有一个包含 x 元素的数组,每 3 秒改变一次,并带有淡入淡出,这样看起来就不难了。问题是我刚刚设法在初始页面加载时显示淡入淡出动画,但不是在每个单词更改时都显示。

这是我的动画:

animations : [
  trigger('fadeAnimation', [
    state('in', style({opacity: 1})),
    transition(':enter', [
      style({opacity: 0}),
      animate(600)
    ]),
    transition(':leave',
      animate(600, style({opacity: 0})))
  ])
]

这是我的 HTML 元素:

<span *ngIf="wordCarousel" id="word-carousel"
      #wordCarousel [@fadeAnimation]="'in'">{{wordCarousel[0]}}</span>

这是我更改单词的地方:

@ViewChild('wordCarousel', {static: false}) wordCarouselEl: ElementRef;

wordCarousel = [
  'Hallo',
  'Hello',
  'Servus'
];
wordCounter = 1;

ngAfterViewInit() {
  if (this.wordCarousel) {
    setInterval(() => {
      this.wordCarouselEl.nativeElement.innerHTML = this.wordCarousel[this.wordCounter];
      this.wordCounter++;
      if (this.wordCounter >= this.wordCarousel.length) {
        this.wordCounter = 0;
      }
    }, 3000);
  }

您可以在这里找到一个工作示例:https ://angular-ivy-gsunum.stackblitz.io

谢谢你帮我找到问题。

标签: javascriptangulartypescriptanimation

解决方案


Jo,我更喜欢用(animation.done)来控制动画何时结束。所以我不能使用:enterand :leave。如果您在 SO 建议中看到我的答案,并且您有两个动画,一个使用两个 div,另一个只使用一个。

想象一下:

animations: [
    trigger("fadeAnimation", [
      transition("false=>true", [
        style({ opacity: 0 }), //At begin animation, opacity=0
        animate("2500ms", style({ opacity: 1 }))  //the animation makes opacity=0 to opacity=1
      ]),
      //the animate("2500ms 2000ms" means that the animation spend 2500ms, 
      //but start after 2000ms. So opacity=1 2000ms, then goes to 0 in 2500ms
      transition("true=>false", [
        //here don't use a "initial style", simply makes opacity goes to 0
        animate("2500ms 2000ms", style({ opacity: 0 }))])
    ])
  ]

看看这些值是如何为假和真的,它没有必要定义一个状态'in'

你的 .html 喜欢:

    <span  id="word-carousel"
          [@fadeAnimation]="toogle" (@fadeAnimation.done)="nextWord($event)">
         {{wordCarousel[wordCounter]}}
    </span>

看到这[fadeAnimation]等于一个“变量”,如果我们将变量从 true 更改为 false 并且从 false 更改为 true 动画开始,所以

  toogle:boolean=true;  //declare the variable "toogle"

  ngAfterViewInit() { //in ngAfterViewInits "begins" the animation
                      //see that we use a setTimeout, we want that Angular
                      //"paint" the elements and, after, change the variable
    setTimeout(()=>{
       this.toogle=false;
    })
  }

嗯,函数 nextWord

nextWord(event: any) {
      //we change the toogle
      this.toogle = !this.toogle;

      //if event.fromState (the value of the animation) is true (when pass from true to false)
      if (event.fromState)
        this.wordCounter = (this.wordCounter + 1) % this.wordCarousel.length;
  }

堆栈闪电战


推荐阅读