Sebastianb Sebastianb - 19 days ago 5
Javascript Question

Angular: Fade in/out without including module NgAnimate

I'm building a small web app in Angular that includes a form with a "save changes" button.

I'd like to show a green tick signifying a correct update of the data, with a quick fade-in/fade-out animation.

I don't think it's worth adding a 20-ish Kb module just for that animation (I don't need to animate any other part of the app).

Is there an alternative way to perform a simple animation such as this without including NgAnimate, that preferably keeps in line with the "Angular way"?

Answer

Yes, there is a way - you can make use of CSS animations, $timeout and ng-class. Here is an example.

Basically you toggle the flag in parent controller

ctrl.showCheckmark = function() {
    ctrl.isShowingCheckmark = true;

    $timeout(function() {
        ctrl.isShowingCheckmark = false;
    }, 2000);
}

and watch the changes in checkmark component.

When the flag changes you set visibility and fade-in flags:

$ctrl.show = function() {
    $ctrl.isShowing = true;

    $timeout(function() {
        $ctrl.fadeIn = true;
        $ctrl.fadeOut = false;
    });
};

using $timeout to wait for previous $digest to finish and render ng-if="$ctrl.isShowing".

All that's left is writing some CSS animations and it is super easy.

Comments