Fade in(out) Animations in Angular

Oleh Teslenko
3 min readSep 15, 2022

--

Photo by Linus Nylund on Unsplash

Animation is a very important part of any web application. It brings life to your code. If your context appears and disappears smoothly it will be more convenient and pleasant for the user. Such apps are always in high demand among users.

We have to create a function with parameters: ‘timingIn’ — time in milliseconds for appear element, and ‘height’ — if you want to change the height of the element. I recommend using the ‘height’ param.

// animation.tsexport function FadeIn(timingIn: number, height: boolean = false): AnimationTriggerMetadata  {
return trigger('fadeIn', [
transition(':enter', [
style(height ? { opacity: 0 , height: 0, } : { opacity: 0, }),
animate(timingIn, style(height ? { opacity: 1, height: 'fit-content' } : { opacity: 1, })),
]),
]);
}

Next step — import it into our ‘animation.component.ts’ file:

// animation.component.tsimport {FadeIn} from '../animation';

@Component({
selector: 'app-animation',
templateUrl: './animation.component.html',
animations: [FadeIn(200, true)]
})

And then set the trigger into an HTML file:

// animation.component.html<p *ngIf=someDynamicValue
[@fadeIn]
>Hello</p>
You will get a result like this gif

If you want that your element fade in and fade out by one function, we can expand the previous one:

export function FadeInOut(timingIn: number, timingOut: number, height: boolean = false): AnimationTriggerMetadata  {
return trigger('fadeInOut', [
transition(':enter', [
style(height ? { opacity: 0 , height: 0, } : { opacity: 0, }),
animate(timingIn, style(height ? { opacity: 1, height: 'fit-content' } : { opacity: 1, })),
]),
transition(':leave', [
animate( timingOut, style(height ? { opacity: 0, height: 0, } : { opacity: 0, })),
])
]);
}

We just added one more parameter ‘timingOut’ into our function and transition for fade-out animation.

Changes in animation.component.ts:

// animation.component.tsimport {FadeInOut} from '../animation';

@Component({
selector: 'app-animation',
templateUrl: './animation.component.html',
animations: [FadeInOut(200, 300, true)]
})

Changes in animation.component.html:

// animation.component.html<p *ngIf=someDynamicValue
[@fadeInOut]
> Hello / Bye </p>
might be a result

It’s a really simple example, but very useful. Thanks for reading. If you like this article, please 👏 or write a comment.

--

--