angular 2 ngIf and CSS transition/animation

前端 未结 7 1775
予麋鹿
予麋鹿 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:48

    One way is to use a setter for the ngIf property and set the state as part of updating the value.

    StackBlitz example

    fade.component.ts

     import {
        animate,
        AnimationEvent,
        state,
        style,
        transition,
        trigger
      } from '@angular/animations';
      import { ChangeDetectionStrategy, Component, Input } from '@angular/core';
    
      export type FadeState = 'visible' | 'hidden';
    
      @Component({
        selector: 'app-fade',
        templateUrl: './fade.component.html',
        styleUrls: ['./fade.component.scss'],
        animations: [
          trigger('state', [
            state(
              'visible',
              style({
                opacity: '1'
              })
            ),
            state(
              'hidden',
              style({
                opacity: '0'
              })
            ),
            transition('* => visible', [animate('500ms ease-out')]),
            transition('visible => hidden', [animate('500ms ease-out')])
          ])
        ],
        changeDetection: ChangeDetectionStrategy.OnPush
      })
      export class FadeComponent {
        state: FadeState;
        // tslint:disable-next-line: variable-name
        private _show: boolean;
        get show() {
          return this._show;
        }
        @Input()
        set show(value: boolean) {
          if (value) {
            this._show = value;
            this.state = 'visible';
          } else {
            this.state = 'hidden';
          }
        }
    
        animationDone(event: AnimationEvent) {
          if (event.fromState === 'visible' && event.toState === 'hidden') {
            this._show = false;
          }
        }
      }
    

    fade.component.html

     

    example.component.css

    :host {
      display: block;
    }
    .fade {
      opacity: 0;
    }
    

提交回复
热议问题