【问题标题】:Angular ViewChild and ComponentFactoryResolver - keep state aliveAngular ViewChild 和 ComponentFactoryResolver - 保持状态
【发布时间】: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 这就是我最终所做的 - 谢谢

标签: angular angular-directive


【解决方案1】:

如果你想在动态创建的组件中添加文本

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

【讨论】:

    猜你喜欢
    • 2023-01-25
    • 1970-01-01
    • 2012-03-09
    • 2018-03-29
    • 1970-01-01
    • 2012-04-14
    • 2011-04-05
    相关资源
    最近更新 更多