Set Angular animation param with Host Binding
Asked Answered
H

3

6

I have been trying to set animation param using @HostBinding decorative, but it seems not to work, what am I missing

animations: [
    trigger('animateMe', [
      state('void', style({ opacity: 0 })),
      transition(':enter, :leave', [ // void <=> *
        animate('{{ easeTime}}ms {{ transitionTimingFn }}')
      ])
    ])
  ]

and HostBinding

@HostBinding('@animateMe') state = {
    value: 'void',
    params: {
      easeTime: 5000
    }
  };
Haloid answered 9/4, 2018 at 4:59 Comment(0)
W
12

If you add a getter function to the host binding property you can set the animation params.

trigger: any;
easingTime = 5000;

@HostBinding('@animateMe') 
get fn() {
    return {
        value: this.trigger,
        params: {
            easeTime: this.easingTime
        }
    }
};
Wagshul answered 25/7, 2018 at 15:2 Comment(1)
This works like a charm and should be marked as the correct answer.Housebreaking
D
3

Animations in the host element should be handled something like this:

animations: [
    trigger('toggleDrawer', [
        state('closed', style({
            transform: 'translateX(0)'
        })),
        state('opened', style({
            transform: 'translateX(80vw)'
        })),
        transition('closed <=> opened', animate(300))
    ])
]

And HostBinding / HostListener

private state: 'opened' | 'closed' = 'closed';

// binds the animation to the host component
@HostBinding('@toggleDrawer') get getToggleDrawer(): string {
    return this.state === 'closed' ? 'opened' : 'closed';
}

@HostListener('@toggleDrawer.start', ['$event']) startDrawerHandler(event: any): void {
    console.log(event);
}

@HostListener('@toggleDrawer.done', ['$event']) doneDrawerHandler(event: any): void {
    console.log(event);
}

Keeping in mind that the HostListeners will be executed on load with the event from state void (fromState: "void"), I don't know if this can be prevented from the animation declaration or if you only need to make a conditional inside the HostListeners if you want to prevent something from happening.

Deacon answered 22/5, 2019 at 9:24 Comment(0)
P
0

Unfortunately, this will not work, as the animations are created before the component is actually generated (this code is in the @Component metadata).

Any code outside the class will not be in the same scope.

Also, I am not sure, but I wouldn't have thought you could bind to an animation using @HostBinding, instead, you can use the animation callbacks like so:

  <ul>
    <li *ngFor="let hero of heroes"
        (@flyInOut.start)="animationStarted($event)"
        (@flyInOut.done)="animationDone($event)"
        [@flyInOut]="'in'">
      {{hero.name}}
    </li>
  </ul>

Ref: https://angular.io/guide/animations#animation-callbacks

Peltate answered 9/4, 2018 at 7:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.