【发布时间】:2018-07-16 16:23:03
【问题描述】:
我使用此处描述的动态组件方法创建了一个选项卡界面:https://angular.io/guide/dynamic-component-loader。
我的问题是——如何在隐藏时维护一个组件的状态?
我在支持中添加了一些代码
import { Directive, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[tabs]'
})
export class TabsDirective {
constructor(public viewContainerRef: ViewContainerRef) { }
}
模板
<div id="tabContent" class="tabContent padded24">
<ng-template tabs></ng-template>
</div>
组件
@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);
}
}
【问题讨论】:
-
你的意思是组件的数据?
-
是的。数据。我记得读过它可以完成,现在我需要找出如何去做。
-
您可以添加服务以保留所需的状态。或者使用 NgRx 之类的库来管理你的状态。
-
@DeborahK 这就是我最终所做的 - 谢谢