2017-09-15 80 views
1

我使用基於角度4框架的Ionic 3。我需要知道,如果我有多個子組件,我可以一個一個地異步加載它們:角度4:逐個加載組件

  1. 加載父項;
  2. 加載第一個孩子;
  3. 當第一個孩子加載時,加載第二個孩子;
  4. 當第二子加載,加載第三子

例如我有孩子一個父組件app.module.ts

@NgModule({ 
declarations: [ 
    AppComponentPage 
], 
imports: [ 
    IonicPageModule.forChild(AppComponentPage), 
    ChildOneComponentModule, 
    ChildTwoComponentModule, 
    ChildThreeComponentModule, 
    ChildFourComponentModule, 
], 
entryComponents: [ 
    AppComponentPage 
]}) 
export class AppComponentPageModule {} 

app.component.ts

import { Component } from '@angular/core'; 
//import all child components 

@Component({ 
    selector: 'app-parent-component', 
    template: ` 
     <child1-component></child1-component> 
     <child2-component></child2-component> 
     <child3-component></child3-component> 
     <child4-component></child4-component> 
    ` 
}) 
export class AppComponentPage { 

    //HOW TO LOAD? 

} 
+0

利用setTimeout和ngIf –

+1

你是什麼意思「異步加載組件」?你的意思是「一個接一個地顯示它們,每N秒」?還有別的嗎? –

+0

你想要加載什麼?什麼是「一個接一個」。 「一個接一個」加載時你期望獲得什麼知識? –

回答

2

在每個子組件的方法,增加一個輸出:

@Output 
initialized = new EventEmitter<boolean>(); 

和當您決定組件初始化(或加載,如您的問題所述)時發出事件,並且可以顯示下一個事件:

ngOnInit() { 
    ... 
    this.initialized.emit(true); 
} 

在父組件,有一個計數器:

counter = 0; 

遞增計數器每一個部件進行初始化時,與直到計數器被允許它被顯示不顯示部件:

<child1-component (initialized)="counter++"></child1-component> 
<child2-component (initialized)="counter++" *ngIf="counter > 0"></child2-component> 
<child3-component (initialized)="counter++" *ngIf="counter > 1"></child3-component> 
<child4-component (initialized)="counter++" *ngIf="counter > 2"></child4-component> 
1

也許你的意思是:

<child1-component *ngFor="let child of children"></child1-component> 
class MyComponent { 
    children:any[] = []; 

    load() { 
    Observable.interval(1000).take(5).subscribe(e => this.children.push(e)); 
    } 
} 

如果要添加不同的組件,你可以像使用Angular 2 dynamic tabs with user-click chosen components