⚠️ This lesson is retired and might contain outdated information.

Animate Adding and Removing Angular Elements with ngIf

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 9 months ago

A common use-case for an Angular animation is to animate an element into the DOM. This is achieved with a combination of ngIf and the “void” state so that you have complete control over how the element appears and how it leaves.

[00:00] You could also use the void state in combination with adding and removing elements with NGIF. Let's add a button with a click on toggle click. Let's call this toggle. This is going to flip this value, let's say is here, so on toggle click, this dot is here is equal to the flip of this is here.

[00:24] We'll start with is here set to faults. In my DIV, I'll say NGIF is here. When I hit save, the black box is gone. I'll click toggle, go up here, I'll click toggle, it will go away. Toggle, it will appear. Toggle, it will go away. You'll notice the delay when it was leaving was because it was animating out to that void state.

[00:48] Let's go ahead and set the void state again. I'm just going to copy and paste this style, but this time I'm going to set the transform of the void state to translate Y negative 100 percent. This is going to move that element up negative 100 percent, so that when I click toggle, it will slide down, and toggle, it will slide back up.

[01:13] It's taking 100 percent of the height of this and moving it up. That's where the void state is. The void state is up above the browser. When I click toggle, it slides it down, and toggle, it slides it back up. It's going to and from this.

[01:28] I don't have to define the positioning here or here, because this transform is just in relation to the default position, and these are already at the default position. You can just go ahead and toggle this. We'll go to stop. We'll go to go. Toggle it again, stop. Nothing happens. Toggle go, stop, toggle.

Eric Babin
Eric Babin
~ 8 years ago

Just an FYI, the plunk doesn't seem to be working at the moment.

izdb
izdb
~ 8 years ago

Is there a way to use this method when the ngIf contains a router-outlet? Seems to break routing making the whole animation system unusable

faye
faye
~ 4 years ago

How can I do something similar when the ngIf is placed on a child component. I have an issue where the animation works on enter, but not on leave.

Markdown supported.
Become a member to join the discussionEnroll Today