Angular 4 同一组件之间的动画

Fra*_*sco 5 angular

我对具有相同组件路径的动画有疑问。例如。我有这条路线:

{路径:'产品/类别/:类别',组件:CategoryComponent},

首先,我解决了路由参数的问题,因为当我在同一组件之间导航时,它们不会刷新 ngOnit() 函数。但现在我已经向我的应用程序添加了动画,并且如果我从 HomeComponent 转到 CategoryComponent,效果会很完美。但是,如果我使用不同的参数从 CategoryComponent 转到 CategoryComponent ,则动画将不起作用。

这是我的动画文件:

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

// Component transition animations
export const slideInDownAnimation: AnimationEntryMetadata =
  trigger('routeAnimation', [
    state('*',
      style({
        opacity: 1,
        transform: 'translateX(0)'
      })
    ),
    transition(':enter', [
      style({
        opacity: 0,
        transform: 'translateX(-100%)'
      }),
      animate('0.5s ease-in')
    ]),
    transition(':leave', [
      animate('0.5s ease-out', style({
        opacity: 0,
        transform: 'translateY(100%)'
      }))
    ])
  ]);
Run Code Online (Sandbox Code Playgroud)

这是我的 CategoryComponent.ts

import { Component, OnInit, EventEmitter,Input, Output,HostBinding} from '@angular/core';
import { Pipe, PipeTransform } from '@angular/core';

import {FirebaseService} from '../../services/firebase.service';
import { AngularFireDatabase, FirebaseListObservable,FirebaseObjectObservable} from 'angularfire2/database';
import {Router, ActivatedRoute, Params,ParamMap} from '@angular/router';
import * as firebase from 'firebase';
import { Observable } from 'rxjs';
import {Subject} from 'rxjs';
import { routerTransition } from '../../router.animations';
import { slideInDownAnimation } from '../../animations';

import { FlashMessagesService } from 'angular2-flash-messages';
@Component({   
  host: {
     '[@routeAnimation]': 'true'
   },
  selector: 'app-category',
  templateUrl: './category.component.html',  
  styleUrls: ['./category.component.css'],  
  animations: [ slideInDownAnimation ]
})
export class CategoryComponent implements OnInit {
  @HostBinding('@routeAnimation') routeAnimation = true;
  @HostBinding('style.display')   display = 'block';
  @HostBinding('style.position')  position = 'absolute';
  products:any;
  search:any;
  imageUrls:any = [];
  imgSelected: any;
  counter:any;
  image:any;
  images:any;
  myimage:any;
  count:any;
  sub:any;  
  i:any;
  category:any;
  fakeimage:any;  
  constructor(
    private firebaseService: FirebaseService,
    private router:Router,
    public af:AngularFireDatabase,
    private route:ActivatedRoute,    
    private flashMessage:FlashMessagesService) {


  }

ngOnInit() {

    this.counter = 0; 

    var params;
    this.sub = this.route.paramMap
      .switchMap((params: ParamMap) =>
      this.firebaseService.getProductsByCategory(params.get('category'))).subscribe(products => {
      this.products = products;
      this.count = products.length;
    });;


 }

  returnImage(key,url){
   this.imageUrls.push(new ImageUrl(key,url));
  }
  searchProps(){    
    this.firebaseService.getProductsByTitle(this.search.toLowerCase()).subscribe(products => { 
      this.products = products;
    });
  }

getProductsByTitle(title){
  console.log('here');    
    this.firebaseService.getProductsByTitle(title.toLowerCase()).subscribe(products => { 
      this.products = products;
    }); 

}
getImageUrl(prodid) {
        // Go call api to get poster.  
        var data = ''; 
        var that = this;
        this.firebaseService.getProductImages(prodid).subscribe(images => { 
          this.image = images[0];
          var img = this.image;
          if(this.image != null){
            let storageRef = firebase.storage().ref();
            let spaceRef = storageRef.child(this.image.path);
            storageRef.child(img.path).getDownloadURL().then(function(url) {
              that.returnImage(img.$key,url);

              }).catch(function(error) {
                // Handle any errors
              });
          }             
        });
}
  ngOnDestroy() {
    this.sub.unsubscribe();
  }

}
export class ImageUrl {
  url: string;
  id:string;
  constructor(public _id:string,public _url: string) {

  }
}
Run Code Online (Sandbox Code Playgroud)

知道我能在这里做什么吗?

谢谢。

小智 3

你击中了要害。当从一个路由参数转到另一个使用相同组件的路由参数时,ngOnInit 不会再次被触发;仅内容被换出。

路由器被设计成以这种方式工作,即使路由参数发生变化也可以使用相同的组件实例。

Github 上有一个主题(https://github.com/angular/angular/issues/17349)讨论了这个问题。该帖子中来自 Matsko 的 Plunker 显示了应用程序的工作版本,该应用程序使用自定义 RouteReuseStrategy 来强制重新加载组件。