How does “Angular 2.0 for TypeScript” (alpha) animation work?

后端 未结 2 853
半阙折子戏
半阙折子戏 2021-01-01 18:42

I am very new in the Angular scene. I just started to learn Angular 2.0 for TypeScript and I was wondering, how the animation (like in a simple HTML with jQuery) works in An

相关标签:
2条回答
  • 2021-01-01 19:05

    You can use CSS, or AnimationBuilder

    For the CSS way you can check this example from their repo that does exactly what you are looking for.

    With AnimationBuilder you can simulate the same behavior like this

    First you set up the template that'll hold the button and div to toggle

    @Component({
      // Setting up some styles
      template: `
        <div animate-box #box="ab"  style="height:0; width:50%; overflow: hidden;">Some content</div>
        <button (click)="box.toggle(visible = !visible)">Animate</button>
      `,
      directives : [AnimateBox] // See class below
    })
    

    Then you create the directive that will handle the animation

    @Directive({
      selector : '[animate-box]',
      exportAs : 'ab' // Necessary, we export it and we can get its 'toggle' method in the template
    })
    class AnimateBox {
      constructor(private _ab: AnimationBuilder, private _e: ElementRef) {}
    
      toggle(isVisible: boolean = false) {
        let animation = this._ab.css();
        animation
          .setDuration(1000); // Duration in ms
    
        // If is not visible, we make it slide down
        if(!isVisible) {
    
          animation
            // Set initial styles
            .setFromStyles({height: '0', width: '50%', overflow: 'hidden'})
            // Set styles that will be added when the animation ends
            .setToStyles({height: '300px'})
        } 
        // If is visible we make it slide up
        else {
          animation
            .setFromStyles({height: '300px', width: '50%'})
            .setToStyles({height: '0'})
        }
    
        // We start the animation in the element, in this case the div
        animation.start(this._e.nativeElement);
      }
    }
    

    Reference

    • Animation API, it's super simple, really, really simple.

    Notes

    This is a temporary API, the new one called ngAnimate 2.0 is not yet available. But you can check what's new in @matsko's talk at AngularConnect - ngAnimate 2.0.

    Here's a plnkr with a repro.

    I hope it helps.

    0 讨论(0)
  • 2021-01-01 19:20

    For your simple "animation" you only need ng-if:

    <div (click)="showDiv2 = !showDiv2">toggle</div>
    <div *ng-if="showDiv2">div 2</div>
    

    BTW, Angular 2 animation is not available yet. The animations documentation has landed.

    0 讨论(0)
提交回复
热议问题