Angular 6 Animation Tutorial

Angular 6 Animation Tutorial

Let's say for instance that we want our list of user's on the user's page to fade in when the component loads. We can use Angular's powerful animation library to help us achieve this.
In order to gain access to the animation library, we have to first install it from the console:
> npm install @angular/animations@latest --save
Then, we add it to the imports of /src/app/app.module.ts:
// Other imports removed for brevity
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
  ...
  imports: [
    // other modules removed for brevity
    BrowserAnimationsModule
  ],
})
Next, open up /src/app/users/users.component.ts and add the following to the top imports:
import { trigger,style,transition,animate,keyframes,query,stagger } from '@angular/animations';
Then, in the component decorator, add the following animations property with the associated code:
@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.scss'],

  // Add this:
  animations: [
    trigger('listStagger', [
      transition('* <=> *', [
        query(
          ':enter',
          [
            style({ opacity: 0, transform: 'translateY(-15px)' }),
            stagger(
              '50ms',
              animate(
                '550ms ease-out',
                style({ opacity: 1, transform: 'translateY(0px)' })
              )
            )
          ],
          { optional: true }
        ),
        query(':leave', animate('50ms', style({ opacity: 0 })), {
          optional: true
        })
      ])
    ])
  ]
})
Whew, a lot happening here!
  • We start off by defining an animation by giving it a trigger with a name listStagger.
  • Next, we use transition to define when the animations will take place, from one animation state to the other. A wildcard is used to say from any state to any state, in this case.
  • Then, we use query to say that on :enter, we apply an initial style that's hidden and moved on the Y axis by -15px, and make a stagger animation for each sequential element. 
  • At the end, we define an optional :leave animation.
To make this work, visit the /src/app/users/users.component.html file and reference the animation trigger:
<ul [@listStagger]="users$">
Save it, and click on the users icon. You will notice that the list animates in!
There's a lot more to Angular animation, so this is just one potential use case.

Angular 6 Animation Tutorial Angular 6 Animation Tutorial Reviewed by Pakainfo on August 08, 2018 Rating: 5

No comments:

'Heartbroken' family of Nigerian man who died at Calgary airport wants answers

'Heartbroken' family of Nigerian man who died at Calgary airport wants answers Bolante Idowu Alo died following altercation wit...

Powered by Blogger.