September 12, 2016

Angular 2 Animate Example: Creating a Sliding Side Navigation Tutorial

Example

 

 

#1 Project Setup

Animations in Angular 2 are probably easier than you think. In this tutorial we will create a simple side navigation that will leave and enter the screen from the right side. We will use Angular-CLI and TypeScript but you should also be able to adopt the steps to any other project like Ionic 2.

First of all install the latest version of the Angular-CLI. Currently the project is under heavy development. Please make sure to get at least version 1.0.0-beta.11-webpack.8 or higher. To print out your current version use ng --version.

cli-version

If your version is older, remove it, clear the npm cache and reinstall with the following commands:

Right now it is required to give the full version in the npm install command, otherwise you will get an old version! You can check for the latest version number here.

 

 

#2 Required Markup

Since our toolchain is now set up, lets kick of a fresh project with Angular-CLI and add the required markup for our example.

Your app is now running at http://localhost:4200.

httOpen a new console window and create the menu component:

Now include the generated menu to your app:

Add some menu points to the menu:

And some styles:

 

Your output should now look like mine:

added-sidebar

Now we need a toggle button:

Result:

add-hamburger

 

 

#3 Animations

This completes our dummy markup. Now it is time to get started with the actual animation. First of all we need to declare some imports in the component responsible for the animation. This will be our app.component. And create the toggleMenu method.

Since our side navigation is located on the right side of the screen we want it be hidden by default and then slide in from the right side on toggle. There is no need to use *NgIf or something else. We simply move the navigation off the canvas to the right side by using transform:translate. On toggle the navigation will slide back in by resetting the transform to zero.
The animation is declared in the component decorator in app.component.ts and then applied to the planned HTML element using the [@] syntax.

Add the animation definition:

Now we need a variable that holds the current state of the animation (‘in’ or ‘out’). This will be later toggled. The initial state should be ‘out’ in order to hide the navigation by default. Also we are adding now the logic of the toggleMenu method, it will simply toggle the states value.

That’s pretty much it. Last step is to add the animation to the component call in our HTML markup using the already mentioned @ syntax. The first part matches the animations name and the given parameter is the value (‘out’ or ‘in’) from our component.

Before you ship this to production make sure to have the webanimations polyfill included, e.g. by adding this to your index.html:

 

 

#4 Final Result:

You can find the full code here:

Full Code at Github
Example Demo

 

 

 

Related Posts

Can Kattwinkel
Developer at thecodecampus </>


37 responses to “Angular 2 Animate Example: Creating a Sliding Side Navigation Tutorial”

  1. Jimmy says:

    This is awesome thank you!! I just updated my app with it 🙂

    http://parlaybuddy.razartech.com/

  2. Kenneth Abbott says:

    Works great. I have a left and right div that now slide in and out. Now I’m just trying to figure out how to have my main middle content flex div expand when I hide the side navs.

    • krishna says:

      Have anyone got flexible component that expands and contracts while using sidenav

      • Can Kattwinkel says:

        Changing the Contents width is generally a bad idea. Since this affects all elements like paragraphs and so on. It is not only a performance nightmare but also the change of width will result in an unsightly transformation of each content element. Change of line breaks etc.

        Anyway you should be able to apply the same animation trigger to your content element as well. Then you are able to create another transformation that manipulates the content element. Other variant would be to use flexbox.

    • Jarvis says:

      Hi,

      How to Make it slide from left side of the screen to right side

    • How did you get this to come up on the left side of the screen?

    • Germaine says:

      How did you get your left side working. thanks

    • Germaine says:

      hello how can i change the position of the menu to the left side and animate it from left to right. thanks

  3. Jon says:

    Great article. How do you close the menu once a menu item has been selected?

    Thanks.

    • Can Kattwinkel says:

      use (click) binding to call a method in your component. The method triggers this.router.navigate([“xx”]) and this.toggleMenu();

  4. Janne Harju says:

    How can I detect when component is not changed but data is. My goal is to change every 5 seconds between two pages which are like hero/0 and hero/1. Animation is working when I click panel link but when page is changed from timer page is changed without animation.

  5. Alejandro Hernández Loza says:

    hi how can i change te position of the menu to te left side and animate it from left to right

  6. Radek Poland says:

    Hi, Thanks for your great article. Simple, clean, well explained, that exactly what I need. Cheers!

  7. atul says:

    hi, thanks for giving nice tutorial it’s very helpful.

  8. saurabh says:

    It is giving me error – Please include either “BrowserAnimationsModule” or “NoopAnimationsModule” in your application. I have added them in my app.module.ts

    import { BrowserAnimationsModule } from ‘@angular/platform-browser/animations’;

    imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule.forRoot(appRoutes),
    BrowserAnimationsModule
    ],

    and installed npm install @angular/animations –save

    done everything but error is still there

    • AshGoTheKey says:

      Same error…

    • TNR says:

      @saurabh & @AshGoTheKey:

      I was having the same error message show up- here is what I did:

      1.) In ‘app.component.ts’, the author imports { trigger, state, style, transition, animate} from ‘@angular/core. According to the official docs, they should be imported from ‘@angular/animations.’

      (https://angular.io/guide/animations for reference)

      2.) Ensure that all of the logic is in ‘app.component.ts’, and that none of it is in menu.component.ts ( I made this mistake initially.) Only the menu.component.css and menu.component.html files should be modified in he menu folder.

      Hope this helps.

      • Can Kattwinkel says:

        Thanks TNR. This article was written when animation was still part of @angular/core. I’ve updated the information imports.

  9. SKS says:

    Hi

    I am getting below URL.

    ERROR in F:/xampp/htdocs/furrytails-web-app/src/app/app.component.ts (1,9): Modu
    le ‘”F:/xampp/htdocs/furrytails-web-app/node_modules/@angular/animations/animati
    ons”‘ has no exported member ‘Component’.

  10. BB says:

    This sample is not running on Angular 4.
    Can you upgrade the sample for Angular 4?

  11. Thanks, for this one.

  12. Miomir says:

    Hello, is ti possbile to call toggleMenu, inside navigation, i have X button inside menu to close the nav. Only problem is thta (click)=’toggleMenu’ does not work inside component menu?

    • Can Kattwinkel says:

      Sure but you have to create an output event emitter in the menu component. On your button you call .emit method of the created event emitter.

      Then in your AppComponent:

  13. Penny says:

    Hi, thanks for the tutorial! The animation works for me but the ease-in-out transition has no effect. I’m using Chrome so I don’t need the polyfill. Any suggestion?

  14. sushrut singh sisodiya says:

    I want to close the navigation on clicking outside the navigation area please help me with this

  15. Saurabh Koshatwar says:

    Hi, thanks for the tutorial!
    To change the position of the menu to the left side and animate it from left to right do following changes

    1) menu.css

    :host {
    background:#2eafe5;
    color: #fff;
    position: fixed;
    left: auto;
    top: 0;
    left: 0;
    bottom: 0;
    width: 20%;
    min-width: 250px;
    z-index: 2;
    font-family: Arial, “Helvetica Neue”, Helvetica, sans-serif;
    }

    ul {
    font-size: 18px;
    line-height: 3;
    font-weight: 400;
    padding-top: 50px;
    list-style: none;
    }

    2) app.component.css :

    import {Component, trigger, state, style, transition, animate} from ‘@angular/animations’;

    @Component({
    selector: ‘app-root’,
    templateUrl: ‘./app.component.html’,
    styleUrls: [‘./app.component.css’],
    animations: [
    trigger(‘slideInOut’, [
    state(‘in’, style({
    transform: ‘translate3d(0, 0, 0)’
    })),
    state(‘out’, style({
    transform: ‘translate3d(-100%, 0, 0)’
    })),
    transition(‘in => out’, animate(‘400ms ease-in-out’)),
    transition(‘out => in’, animate(‘400ms ease-in-out’))
    ]),
    ]
    })
    export class AppComponent {
    title = ‘app works!’;

    toggleMenu() {

    }
    }

  16. priya says:

    Thanks.Its working for me in angular4.But how to hide toggle button from login and register page.

Leave a Reply

Add code to your comment in Markdown syntax.
Like this:
`inline example`

```
code block
example
```

Your email address will not be published.