angular 2 ngIf and CSS transition/animation

前端 未结 7 1778
予麋鹿
予麋鹿 2020-11-29 16:23

I want a div to slide in from the right in angular 2 using css.

  

7条回答
  •  感情败类
    2020-11-29 16:58

    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:

    animations: [
      trigger('fadeInOut', [
        transition(':enter', [   // :enter is alias to 'void => *'
          style({opacity:0}),
          animate(500, style({opacity:1})) 
        ]),
        transition(':leave', [   // :leave is alias to '* => void'
          animate(500, style({opacity:0})) 
        ])
      ])
    ]
    

    Do not forget to add imports

    import {style, state, animate, transition, trigger} from '@angular/animations';
    

    The relevant component's html's element should look like:

    element

    I built example of slide and fade animation here.

    Explanation on 'void' and '*':

    • void is the state when ngIf 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 when ngIf is set to true).

    Notice (taken from angular docs):

    Extra declare inside the app module, import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

    Angular animations are built on top of the standard Web Animations API and run natively on browsers that support it. For other browsers, a polyfill is required. Grab web-animations.min.js from GitHub and add it to your page.

提交回复
热议问题