3

Say you got two divs like this on the component.html

<div *ngIf="htmlSegment == 'a" >
    {{someMessage}}
</div>


<div *ngIf="htmlSegment == 'b" >
    {{someMessage}}
</div>

When you set the htmlSegment to a or b, we know that the truthy value segment comes alive and the other would disappear. No issues there.

But, what does it take to make the appearance and the disappearance of those segments come alive with some transitioning effects; such as fading in or out etc?

And is it possible to make sure, the transition starts after the dom is done in the new htmlSegment? ( This is so that the user does not experience any flashing or page jerking except the awesome fade in and fade out only. )

Average Joe
  • 4,521
  • 9
  • 53
  • 81
  • Does this answer your question? [angular 2 ngIf and CSS transition/animation](https://stackoverflow.com/questions/36417931/angular-2-ngif-and-css-transition-animation) – duhaime Mar 19 '22 at 12:06

1 Answers1

0

The Animate module does not animate your HTML elements, but when Animate notice certain events, like hiding or showing of an HTML element, the element gets some pre-defined styles(or classes) which can be used to make animations.

Add animate module to your project:

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

Add animation property to your component:

animations: [
  trigger('heroState', [
    state('a', style({
     backgroundColor: 'yellow',
     opacity:0.5
    })),
    state('b', style({
     backgroundColor: 'black',
     opacity:1
    })),
    transition('a => b', animate('100ms ease-in')),
    transition('b => a', animate('100ms ease-out'))
  ])
]

The trigger will be called when herostate change.

At the end, your HTML code will be:

<div *ngIf="htmlSegment == 'a" 
 [@heroState]="a">
    {{someMessage}}
</div>

<div *ngIf="htmlSegment == 'b"
[@heroState]="b" >
    {{someMessage}}
</div>

I can't create an Angular2 online sample of this code but I create an AngularJS online sample for sensing what exactly happen in animations.(for changing animation, you can change 'nga-slide-down' class to 'nga-fade' or your own class)

Check Online(AngularJS - check auto-run js at the right panel and click on change button)

Iman Bahrampour
  • 6,180
  • 2
  • 41
  • 64