Skip to content

Instantly share code, notes, and snippets.

@codephobia
Created August 20, 2019 19:25
Show Gist options
  • Select an option

  • Save codephobia/52fa250b159dbb8f6a95ae922cb01e77 to your computer and use it in GitHub Desktop.

Select an option

Save codephobia/52fa250b159dbb8f6a95ae922cb01e77 to your computer and use it in GitHub Desktop.
Example Angular animations toggle
import {
trigger,
transition,
style,
animate,
query,
group,
useAnimation,
animation
} from '@angular/animations';
let activeToggleAnimation: ToggleAnimationType = 'DESKTOP';
export type ToggleAnimationType = 'DESKTOP' | 'MOBILE';
export function isToggleAnimationTypeEnabled(type: ToggleAnimationType): boolean {
return activeToggleAnimation === type;
}
export const DESKTOP_ANIMATION = animation([
...
]);
export const MOBILE_ANIMATION = animation([
...
]);
export function desktopAnimation(
toState: string | boolean,
fromState: string | boolean
): boolean {
return (
toState === false &&
fromState === true &&
isToggleAnimationTypeEnabled('DESKTOP')
);
}
export function mobileAnimation(
toState: string | boolean,
fromState: string | boolean
): boolean {
return (
toState === true &&
fromState === false &&
isToggleAnimationTypeEnabled('MOBILE')
);
}
export function setToggleAnimationType(type: ToggleAnimationType): void {
activeToggleAnimation = type;
}
export const toggleAnimation = trigger('toggleAnimation', [
transition('void => *', []),
transition(desktopAnimation, useAnimation(DESKTOP_ANIMATION)),
transition(mobileAnimation, useAnimation(MOBILE_ANIMATION)),
]);
import { Component, ChangeDetectorRef, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { breakpoints } from 'src/app/util/breakpoints';
import { WindowService } from 'src/app/services/window.service';
import { setToggleAnimationType, toggleAnimation } from 'src/app/animations/example.animation';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.scss'],
animations: [toggleAnimation]
})
export class ExampleComponent implements OnDestroy {
public isMobile: boolean;
private _windowWidthSub: Subscription;
constructor(
private changeDetectorRef: ChangeDetectorRef,
windowService: WindowService,
) {
// watch window width so we can turn off the animation for mobile
this._windowWidthSub = windowService.width$.subscribe(width => {
const newIsMobile = (width <= breakpoints.mdMax);
// only fire the change if we changed from/to mobile
if (this.isMobile !== newIsMobile) {
this.isMobile = newIsMobile;
const animationType = (this.isMobile) ? 'MOBILE' : 'DESKTOP';
setToggleAnimationType(animationType);
this.changeDetectorRef.markForCheck();
}
});
}
public ngOnDestroy(): void {
if (this._windowWidthSub) {
this._windowWidthSub.unsubscribe();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment