First you have omitted break
in in switch statement, which is doesn't stop after reaching 'mobile' case. So if you put console.log in each method(loadMobileContent/loadDesktopContent), you will see after switching from mobile to desktop version each method is called:
switch(newDevice){
case 'mobile': this.loadMobileContent();
case 'desktop': this.loadDesktopContent();
}
Fix:
switch (newDevice) {
case 'mobile':
this.loadMobileContent();
break;
case 'desktop':
this.loadDesktopContent();
break;
}
Also change moveRouterOutlet()
method to:
moveRouterOutlet(fromOutlet: ViewContainerRef, toOutlet: ViewContainerRef): void {
fromOutlet.clear();
toOutlet.createEmbeddedView(this.tpl);
}
StackBlitzh Demo
Here is another solution with declarative approach with using ngIf else feature:
<div>
<h1 *ngIf="device !== 'mobile' else tpl">Desktop</h1>
<!-- <div #desktopOutlet></div> -->
</div>
<div>
<h1 *ngIf="device !== 'desktop' else tpl">Mobile</h1>
<!-- <div #mobileOutlet></div> -->
</div>
<ng-template #tpl>
<router-outlet></router-outlet>
</ng-template>
StackBlitz Demo
Hey thanks for the effort. Problem with both solutions is that it will
reinitialize the component rendered through the . I
need to keep the component state as I switch viewports. that's why I'm
trying to detach it, not clear it.
Ok, then you can detach ViewRef
from outlet and insert to another:
moveRouterOutlet(fromOutlet: ViewContainerRef, toOutlet: ViewContainerRef): void {
let detached = fromOutlet.detach();
toOutlet.insert(detached);
}
This will save the component state
Updated StackBlitz