I have created an interface of tabs using the dynamic component approach described here: https://angular.io/guide/dynamic-component-loader.
My question is - how do you maintain state of one component while it is hidden?
I add some code in support
import { Directive, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[tabs]'
})
export class TabsDirective {
constructor(public viewContainerRef: ViewContainerRef) { }
}
Template
<div id="tabContent" class="tabContent padded24">
<ng-template tabs></ng-template>
</div>
Component
@Component({
selector: 'my-tabs',
templateUrl: './tabs.component.html',
styleUrls: ['./tabs.component.css']
})
export class TabsComponent implements OnInit, OnDestroy {
//Empty array to store list of possible tabs. A variable to store the current tab. A Viewchild to render the appropiate Tab content
public tabs = []
currentTab;
@ViewChild(TabsDirective) Tab: TabsDirective;
constructor(
private _tabsService: TabsService,
private componentFactoryResolver: ComponentFactoryResolver,
) { }
ngOnInit() {
this.tabs = this._tabsService.getTabItems();
this.currentTab = this.tabs[0]
}
onSelect(tab) {
this.router.navigate(['/admin', tab.id])
}
//Load appropiate tab content depending on select tab
loadComponent() {
var result = this.tabs.filter((obj) => {
return obj.id == this.currentTab;
});
let tabItem = result[0];
let componentFactory = this.componentFactoryResolver.resolveComponentFactory(tabItem.component);
let viewContainerRef = this.Tab.viewContainerRef;
viewContainerRef.clear();
let componentRef = viewContainerRef.createComponent(componentFactory);
}
}