Подтвердить что ты не робот

Пример завершения функции обратного вызова Angular 2

Я пытаюсь создать функцию, которая будет запускаться в конце анимации в Angular 2 (я использую последнюю версию angular cli).

Я был на Angular Animations, чтобы получить некоторое понимание того, как это будет реализовано, назначив триггер с обратным вызовом в моем примере кода. У меня есть компонент, который анимируется на странице. код имеет следующее:

//first.component.ts

import { Component, OnInit } from '@angular/core';
import { trigger, state, style, animate, transition } from '@angular/core';


@Component({
  selector: 'app-first',
  templateUrl: './first.component.html',
  styleUrls: ['./first.component.css'],
  host: {
    '[@routeAnimation]': 'true',
    '[style.display]': "'block'",
    '[style.position]': "'absolute'"
  },
  animations: [
    trigger('routeAnimation', [
      state('*', style({transform: 'translateX(0)', opacity: 1})),
      transition('void => *', [style({transform: 'translateX(-100%)', opacity: 0}),animate(500)]),
      transition('* => void', animate(500, style({transform: 'translateX(100%)', opacity: 0})))
    ])
  ]
})
export class FirstComponent implements OnInit {

  constructor() { }

  ngOnInit() {

  }

  myFunc() {
  // call this function at the end of the animation.
 }

}

HTML это просто div

<div class="w9914420">
  <h2>
     first-component Works!
  </h2>
</div> 

Честно говоря, я не слишком знаком с JavaScript, поэтому любая помощь или быстрый пример помогут мне лучше понять Angular 2.

4b9b3361

Ответ 1

Это рабочий пример:

import {Component, NgModule, Input, trigger, state, animate, transition, style, HostListener } from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector : 'toggle',
  animations: [
    trigger('toggle', [
      state('true', style({ opacity: 1; color: 'red' })),
      state('void', style({ opacity: 0; color: 'blue' })),
      transition(':enter', animate('500ms ease-in-out')),
      transition(':leave', animate('500ms ease-in-out'))
    ])
  ],
  template: '
  <div class="toggle" [@toggle]="show" 
        (@toggle.start)="animationStarted($event)"
        (@toggle.done)="animationDone($event)"
     *ngIf="show">
    <ng-content></ng-content>
  </div>'
})
export class Toggle {
  @Input() show:boolean = true;
  @HostListener('document:click')
  onClick(){
    this.show=!this.show;
  }

  animationStarted($event) {
    console.log('Start');
  }

  animationDone($event) {
    console.log('End');
  }
}

@Component({
  selector: 'my-app',
  template: '
    <div>
      <toggle>Hey!</toggle>
    </div>
  ',
})
export class App {

}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App, Toggle ],
  bootstrap: [ App ]
})
export class AppModule {}

Plunker

Ответ 2

Теперь Angular2 поддерживает (@animation.start) и (@animation.done) для подключения к анимационным событиям.

Например, вы можете использовать (@routeAnimation.start)=onStart($event), (@routeAnimation.done)=onDone($event) в first.component.html.

Вы можете узнать больше здесь.

Также вы можете увидеть простой пример с first.component.ts на Plunker.

Надеюсь, это поможет!

Ответ 3

А что если мы будем использовать HostBinding???

@HostBinding('@ourAnimate') get ourAnimate() {
    return this.opened ? 'open' : 'closed';
}

Как мы можем поймать состояние "@ourAnimate.done" и затем запустить другую функцию, например? Пожалуйста помогает