I want a div to slide in from the right in angular 2 using css.
<div class="note" [ngClass]="{'transition':show}" *ngIf="show">
<p> Notes</p>
</div>
<button class="btn btn-default" (click)="toggle(show)">Toggle</button>
I works fine if i only use [ngClass] to toggle class and utilise opacity. But li don't want that element to be rendered from the beginning so I "hide" it with ngIf first, but then the transition wont't work.
.transition{
-webkit-transition: opacity 1000ms ease-in-out,margin-left 500ms ease-in-out;
-moz-transition: opacity 1000ms ease-in-out,margin-left 500ms ease-in-out;
-ms-transition: opacity 1000ms ease-in-out,margin-left 500ms ease-in-out ;
-o-transition: opacity 1000ms ease-in-out,margin-left 500ms ease-in-out;
transition: opacity 1000ms ease-in-out,margin-left 500ms ease-in-out;
margin-left: 1500px;
width: 200px;
opacity: 0;
}
.transition{
opacity: 100;
margin-left: 0;
}
One way is to use a setter for the ngIf property and set the state as part of updating the value. When setting the property to true detectChanges() needs to be called to make sure the element gets added back to the dom before the animation state gets changed.
StackBlitz example
example.component.ts
example.component.html
example.component.css
CSS only solution for modern browsers
update 4.1.0
Plunker
See also https://github.com/angular/angular/blob/master/CHANGELOG.md#400-rc1-2017-02-24
update 2.1.0
Plunker
For more details see Animations at angular.io
original
*ngIf
removes the element from the DOM when the expression becomesfalse
. You can't have a transition on a non-existing element.Use instead
hidden
:Am using angular 5 and for an ngif to work for me that is in a ngfor, I had to use animateChild and in the user-detail component I used the *ngIf="user.expanded" to show hide user and it worked for entering a leaving
According to the latest angular 2 documentation you can animate "Entering and Leaving" elements (like in angular 1).
Example of simple fade animation:
In relevant @Component add:
Do not forget to add imports
The relevant component's html's element should look like:
I built example of slide and fade animation here.
Explanation on 'void' and '*':
void
is the state whenngIf
is set to false (it applies when the element is not attached to a view).*
- There can be many animation states (read more in docs). The*
state takes precedence over all of them as a "wildcard" (in my example this is the state whenngIf
is set totrue
).Notice (taken from angular docs):