2

I want to animate a scale-down-then-scale-back effect on every button clicks. Here are what I tried:

<button (click)="clickMe()" [ngClass]="{'animated-button': animated}">Button</button>

Here's my CSS:

@keyframes buttonClickAnimation {
  0% {transform: scale(0.8);}
  100% {transform: scale(1);}
}
.animated-button {
  animation: buttonClickAnimation 0.5s;
}

Here's my component:

...
animated: boolean = false;

clickMe() {
  this.animated = true;
}

This only works on the very first click, which makes sense because my animated variable never gets set back to false. However, if I set it back to false in clickMe(), the animation wouldn't have time to execute. Maybe this isn't even the right way to implement this. Please advise! Thank you.

2 Answers 2

1

Add a delay to setting the animated variable to false.

clickMe() {
  this.animated = true;
  delay(500).then(() => this.animated = false);
}

async function delay(ms: number) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
Sign up to request clarification or add additional context in comments.

1 Comment

Turning this into a directive would be nice, no? (to avoid having to deal with an otherwise rather useless state variable redundandly on every occasion)
0

You can toggle a boolean (true/false) value by appending a !

animated: boolean = false;

clickMe() {
  this.animated = !this.animated;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.