Angular 2中的组件创建顺序

Angular 2中的组件创建顺序

问题描述:

我正在尝试阅读组件列表并在我的页面上动态创建它们。我为此使用ComponentResolver并使用新的@ViewChild方法创建组件。Angular 2中的组件创建顺序

我有一个扩展ComponentCreator类的MainComponent文件。这个ComponentCreator类是所有其他组件可以“扩展”并用于创建其各自子组件的基类。

下面是代码片段,使事情更清晰:

MainComponent.ts

export class MainComponent extends ComponentCreator { 

@ViewChild("target", { read: ViewContainerRef }) target; 

constructor(_componentResolver: ComponentResolver, metaService: MetaService) { 
    super(_componentResolver, metaService, "./src/app/meta.json", "MainComponent"); 
} 

ComponentCreator.ts

export class ComponentCreator{ 

    //declare variables 

    constructor(_componentResolver: ComponentResolver, _metaService: MetaService, _templateUrl: string, _templateName: string) { 
    this._componentResolver = _componentResolver; 
    this._templateUrl = _templateUrl; 
    this._metaService = _metaService; 
    this._templateName = _templateName; 
    } 

    ngAfterViewInit() { 
    //metaService gets the template. It's a json file in which all the child components of Main component are listed 
    this._metaService.getTemplate(this._templateUrl) 
     .subscribe(
     _template => this._template = this.loadComponents(_template), 
     error => this._errorMessage = <any>error); 
    } 

    loadChildComponents(template) { 
    //Create components here 
    //'place' comes from the json file. It's Equal to target. 
    for(let component in jsonData) 
     this._componentResolver.resolveComponent(component).then((factory:ComponentFactory<any>)=> { this.cmpRef = this.place.createComponent(factory)}); 
    } 
} 

我面临的问题是在组件创建的顺序。例如,我有4个子组件,其中2个是纯HTML表格,2个是使用d3绘制的一些图表。尽管我将创建顺序指定为1,2,3,4;渲染的顺序被搞乱了。由于它们全部加载到'target'div内,所以HTML表格在两个图表之前呈现得都很快。

有什么方法可以解决这个问题吗?还是我不得不为表格和图表使用单独的div,以便顺序保持不变?

+0

例子之后,你可以提供证明的问题上Plunker?您提供的代码不会在任何地方使用'target',并且您不清楚如何使用d3。因此很难理解发生了什么事情。 –

+0

只需创建优先级变量并在组件上添加* ngIf – mayur

+0

@GünterZöchbauer我编辑了我的帖子以反映目标的使用情况。我会尝试为它创建一个plunker,但如果你能够使用新的编辑信息来衡量它会很好。 HTML表格的顺序不会改变,并且d3图形的顺序在它们各自的类别中不会改变。但他们彼此混淆。 – DaWanderer

我认为问题在于你在一个for()循环内调用异步代码,这会导致随机顺序。

使用Promise.all(),以确保他们执行一个其他

Promise.all(
    jsonData.map(component => 
    this._componentResolver.resolveComponent(component) 
    .then((factory:ComponentFactory<any>)=> { 
     this.cmpRef = this.place.createComponent(factory); 
    }); 
) 
); 

也见类似的旧DynamicComponentLoaderhttps://github.com/angular/angular/issues/7854#issuecomment-203988888

+1

这可能是正确的。我只是尝试记录组件名称,并看到它们以不同于json中指定的顺序进入。我会尝试使用Promise.all并告诉你这是否可行!谢谢! – DaWanderer