2016-06-01 8 views
1

コンポーネントのリストを読み込み、自分のページに動的に作成しようとしています。私はこれにComponentResolverを使用し、新しい@ViewChildメソッドを使用してコンポーネントを作成しています。コンポーネントの作成順序を角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

でも古いDynamicComponentLoaderのための同様の例を参照してくださいした後、彼らはあなたが問題を示していPlunkerを提供することができる1つを実行していることを確認するには?あなたが提供したコードはどこにでも 'target'を使用していませんし、どのようにd3を使うのかは分かりません。したがって、何が起こっているのかを考えるのは難しいです。 –

+0

優先度の高い変数を作成し、コンポーネントに* ngIfを追加するだけです。 – mayur

+0

@GünterZöchbauer私はターゲットの使用を反映するために投稿を編集しました。私はそれのためのプランナーを作成しようとしますが、それはあなたが新しい編集情報を使用してそれを測定することができれば素晴らしいだろう。 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); 
    }); 
) 
); 

https://github.com/angular/angular/issues/7854#issuecomment-203988888

+1

それは正しいかもしれません。私はちょうどコンポーネント名を記録しようとし、それらがjsonで指定されたものとは異なる順序で来ているのを見た。私はPromise.allを使って、これがうまくいくかどうか教えてくれるでしょう!ありがとう! – DaWanderer

関連する問題