Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to create a cross fade effect in Angular but the images keep pulsating instead of fading into each other. How can I fix it?

animations.ts

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

export const fade = [
  trigger('fade', [
    state('in', style({ 'opacity': '1' })),
    state('out', style({ 'opacity': '0' })),
    transition('* <=> *', [
      animate(500)
    ])
  ])
];

export enum AnimationState {
  IN = 'in',
  OUT = 'out'
}

app.component.ts

export class AppComponent implements OnInit {
  heroImageArray = [
    "https://drscdn.500px.org/photo/277987267/q%3D80_m%3D2000/v2?webp=true&sig=082269b7b07ec17da1847d5c20cffee3a3a91af1f474eb3fd908eba828d5327c",
    "https://drscdn.500px.org/photo/253947845/q%3D80_h%3D450/v2?webp=true&sig=c645b242f19581b17df5bc68d54ee4e5a3c2f5b1ddd41791683ed9c03c455151"
  ];
  heroActiveImage: string =
    "https://drscdn.500px.org/photo/277987267/q%3D80_m%3D2000/v2?webp=true&sig=082269b7b07ec17da1847d5c20cffee3a3a91af1f474eb3fd908eba828d5327c";
  state = AnimationState.IN;

  ngOnInit() {
    this.toggleImg();
  }

  toggleImg() {
    let count = 0;
    setInterval(() => {
      if (count === this.heroImageArray.length) {
        count = 0;
      }
      this.heroActiveImage = this.heroImageArray[count];
      count++;
    }, 3000);
  }

  onDone() {
    this.toggleState();
  }

  toggleState() {
    this.state =
      this.state === AnimationState.IN ? AnimationState.OUT : AnimationState.IN;
  }
}

Stackblitz here: https://stackblitz.com/edit/angular-anim-fade-img-gga34g

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
237 views
Welcome To Ask or Share your Answers For Others

1 Answer

There were some changes needed to be performed but basically I changed the value passed to animate() from 500 to 2000 (no worries, with the changes now you can just adjust the transition time you want by changing the value passed to the animate function), also I moved the block of code to change the image to the toggleState function and reorder the strings in the heroImageArray (that was to prevent the error you mentioned about the first image).

Here you have the code https://stackblitz.com/edit/angular-anim-fade-img-yupxe1?file=app%2Fapp.component.ts

Note: to slow or speed the transition, just change the value passed to the animate function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...