18

I have a sidebar that I am showing / hiding using a boolean like this:

[hidden]='toggleSidebar'

I have been trying to find the correct way to add a transition to this element, but so far have been only partially successful using this method : [class.show]='!toggleSidebar'. Applying css styles to this class only partially works though.

How do I add a slide-in or fade-in animation to an element containing a router-outlet such as this?

<aside [hidden]="toggleSidebar">
  <router-outlet name="aside"></router-outlet>
</aside>

2 Answers 2

21

Using the [hidden] attribute you just can't achieve a transition/animation effect since there are no subsequent step changes but only state changes which reflect either the element is visible or hidden.

What you can do is use opacity and visibility.

<aside class="sidebar" [style.opacity]="toggleSidebar ? '0' : '1'" [style.visibility]="toggleSidebar ? 'hidden' : 'visible'">
  <router-outlet name="aside"></router-outlet>
</aside>

Provide a transition timing for the sidebar for state changes.

.sidebar {
  transition: all .3s;
}

NOTE: Its better to avoid the [hidden] attribute if you look forward to support Internet Explorer 9 and 10. :)

1
  • 5
    This is not the same as [hidden] as it still takes up space on the screen.
    – MadMac
    Commented Oct 22, 2019 at 19:22
13

Desired behaviour can be achieved with ngIf. From official guide:

The void state

The special state called void can apply to any animation. It applies when the element is not attached to a view, perhaps because it has not yet been added or because it has been removed. The void state is useful for defining enter and leave animations.

In example below div shows up from top of the screen when condition evaluates to true.

HTML:

<div *ngIf="panelVisible" [@panelInOut]>....</div>

TS:

 @Component({
    ....
    animations: [
        trigger('panelInOut', [
            transition('void => *', [
                style({transform: 'translateY(-100%)'}),
                animate(800)
            ]),
            transition('* => void', [
                animate(800, style({transform: 'translateY(-100%)'}))
            ])
        ])
    ]
})
2
  • 21
    This would be nice except *ngIf and hidden act differently - ngIf removes the element from the DOM while hidden does not. There might be a case where you just want hidden
    – Daniel
    Commented Jan 23, 2019 at 20:57
  • 3
    One case where you don't want *ngIf: If you are waiting for an <img> tag to load it's image before executing a fade-in animation. Obviously, if the <img> tag doesn't exist, it will not be able to finish loading the image.
    – Trevor
    Commented Feb 11, 2020 at 20:13

Not the answer you're looking for? Browse other questions tagged or ask your own question.