我已经使用此处介绍的动态组件方法创建了标签界面: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);
}
}
答案 0 :(得分:0)
如果要在动态创建的组件中添加文本
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);
componentRef .instance.text = 'Iam dynamically created Text';
}
有关更多信息,请检查以下内容:Angular 2 dynamic tabs with user-click chosen components