我尝试创建一种Viewcontroller服务,它创建(并销毁)动态组件(类似于ViewController ind Ionic)。向新组件添加一些滑动或渐弱动画会很好,但我还不知道如何做到这一点。我知道角度路由器,它允许动画,但我更喜欢不使用路由器的解决方案。
到目前为止,这是我所得到的并且运作良好。
@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);
})
}
现在我想添加一些动画,例如:
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'))
]),
]
但是如何将动画附加到新创建的组件?直接在组件本身内?或者有没有办法使用ComponentFactoryResolver?遗憾的是,角度渲染器无法在服务中使用。