Carlos Villalta Carlos Villalta - 4 years ago 138
Javascript Question

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

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?

Answer Source

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

You can read more about it in the docs, but the jist 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.

Give 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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download