我正在嘗試閱讀組件列表並在我的頁面上動態創建它們。我爲此使用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,以便順序保持不變?
例子之後,你可以提供證明的問題上Plunker?您提供的代碼不會在任何地方使用'target',並且您不清楚如何使用d3。因此很難理解發生了什麼事情。 –
只需創建優先級變量並在組件上添加* ngIf – mayur
@GünterZöchbauer我編輯了我的帖子以反映目標的使用情況。我會嘗試爲它創建一個plunker,但如果你能夠使用新的編輯信息來衡量它會很好。 HTML表格的順序不會改變,並且d3圖形的順序在它們各自的類別中不會改變。但他們彼此混淆。 – DaWanderer