Search code examples
javascripthtmlcssangulargsap

gsap&Angular - onComplete triggering function but can't change variable value


I am using GSAP with my Angular project to implement animation on my custom dropdown menu.

I found that I could collapse my div down to height: 0px, however the border was still present.

My initial thought was to use visibility: hidden by means of using the Angular directive: [hidden]="isHidden" whereby isHidden is a declared variable in the .ts file initialised within the constructor.

I attempted to use the onComplete part of the TweenMax.to(...) to fire off a function that will toggle the isHidden to true/false. However, I found that I couldn't change the Boolean value from here?

I did check that the function fired with a console.log(...), however I couldn't get the variable to change...

Am I doing something wrong?

visible: boolean;

constructor() {
  this.visible = false;
}

toggleDropdown(): void {
  TweenMax.to(dropdown, 1, {css: {height: '0px'}, ease: Power2.easeInOut, onComplete: this.toggleVisibility}
}

toggleVisibility() {
  this.visible = !this.visible;
}

Solution

  • I suspect that, in the toggleVisibility() function, the context (this) is not the same as in toggleDropdown(), because you're not passing it along.

    It's a tricky concept, but you have to pass/bind this to the function you call as a callback :

    ..., onComplete: this.toggleVisibility.bind(this)

    Try to console.log(this) inside toggleVisibility() to see whether the context is correct or not.