2016-06-01 79 views
1

我正在嘗試閱讀組件列表並在我的頁面上動態創建它們。我爲此使用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

回答

0

我認爲問題在於你在一個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