3

I try to create kind of a Viewcontroller service which creates (and destroys) dynamically components (similar like the ViewController ind Ionic). It would be nice to add some sliding or fading animations to the new components, but I could not yet figure out how to do so. I am aware of the angular router and that it allows animations, but I would prefer a solution without using the router.

This is what I have got and works well so far.

@Injectable()
export class ViewControllerService {

constructor( private zone:  NgZone, private resolver: 
ComponentFactoryResolver, private injector: Injector, private 
appRef:ApplicationRef) { 

}

myComponentRef: ComponentRef<MyComponent>;
createMyComponent(data){

this.zone.run( () => {

  if(this.myComponentRef){
    this.myComponentRef.destroy();
  }
  const compFactory = this.resolver.resolveComponentFactory(MyComponent);
  this.myComponentRef = compFactory.create(this.injector);

  //set data to component Input
  this.myComponentRef.instance.data = data;

  //listen to EventEmitter dismiss in component
  this.myComponentRef.instance.dismiss.subscribe(data => { 
    console.log("closing component",data)
    if(this.myComponentRef){
      this.myComponentRef.destroy();

    }
  });

  if (this.appRef['attachView']) { // since 2.3.0
    this.appRef['attachView'](this.myComponentRef.hostView);
    this.myComponentRef .onDestroy(() => {
      console.log("attachView onDestroy",this.myComponentRef)
        this.appRef['detachView'](this.myComponentRef.hostView);

    });
  } else {
    this.appRef['registerChangeDetector'](this.myComponentRef.changeDetectorRef);
    this.myComponentRef.onDestroy(() => {
      console.log("onDestroy",this.myComponentRef)
      this.appRef['unregisterChangeDetector'](this.myComponentRef.changeDetectorRef);

    });
  }

  //attach component to base element
  let div = document.createElement('div');
  div.setAttribute("class","my-class")
  div.appendChild(this.myComponentRef.location.nativeElement)
  document.getElementById("base").appendChild(div);


})
}

Now I would like to add some animations like for example this:

export const slideInOutAnimation = [
trigger('slideInOut', [
state('in', style({
  transform: 'translate3d(0, 0, 0)'
})),
state('out', style({
  transform: 'translate3d(100%, 0, 0)'
})),
transition('in => out', animate('400ms ease-in-out')),
transition('out => in', animate('400ms ease-in-out'))
]),
]

but how to attach animations to the new created component? Directly within the component itself? Or is there a way using the ComponentFactoryResolver for this? The angular Renderer is unfortunately not working in Services.

Chris
  • 4,238
  • 4
  • 28
  • 49

0 Answers0