Is it possible to animate Angular 2's ng-switch
Asked Answered
P

1

10

Is it possible to animate this at all? I have this block of code

div([ngSwitch]="switchState")
  ul(fxLayout="row", fxLayoutAlign="space-between", *ngSwitchCase="0")
   some-list
  ul(fxLayout="row", fxLayoutAlign="space-between", *ngSwitchCase="1")
   second-list  
  ul(fxLayout="row", fxLayoutAlign="space-between", *ngSwitchCase="2")
   third-list

actual switch functionality is working fine, I want to animate it but Im not exactly sure what css property angular plays with, I suspect at the time it doesnt even exist in the DOM, so is it possible to animate new additions to the DOM?

Psychopathology answered 3/2, 2017 at 3:12 Comment(3)
transition-duration would be a good css property to try out.Lazulite
What markup is this?Mindful
It looks like pug/jade to me.Lazulite
M
26

Yes, it is possible to animate ng-switch using Angular2 animation system.

You can read more about it in the docs, but the gist is that you can animate any element that is being added to DOM. When using *ngSwitchCase elements are removed and inserted into the DOM based on condition. This state is called the void state & you can choose what animation to apply as it transitions from void state to being visible.

Given the following markup that uses ngSwitch:

<div [ngSwitch]="val">
   <p *ngSwitchCase="true" [@enterTrigger]="'fadeIn'">Value is TRUE</p>
   <p *ngSwitchCase="false" [@enterTrigger]="'fadeIn'">Value is FALSE</p>
</div>

You can define animations in the component like this:

@Component({
  selector: 'my-app',
  animations: [
    trigger('enterTrigger', [
    state('fadeIn', style({
        opacity: '1',
        transform: 'translateY(50%)'
    })),
    transition('void => *', [style({opacity: '0'}), animate('500ms')])
    ])
  ]
})

Here the void => * transition determines how the element will be animated as it moves from void state to any state (including becoming visible)

Plunkr demo: https://plnkr.co/edit/IPLImRt34esClBg1HZdm?p=preview

P.S. Don't forget to install @angular/animations

Mindful answered 3/2, 2017 at 7:26 Comment(3)
Thank you very much!! This worked!! I can't upvote, not enough rep :)Psychopathology
angular > 4 - don't forget to import BrowserAnimationsModule in app.module.tsYelena
plunkr does not workBoutin

© 2022 - 2024 — McMap. All rights reserved.