angular 4: load components one by one

我只是一个虾纸丫 提交于 2019-12-22 00:16:19

问题


I'm using Ionic 3 with based on angular 4 framework. And I need to know if I have multiple children components can I load them asynchronously, one by one:

  1. Load parent;
  2. Load first child;
  3. When first child loaded, load second child;
  4. When second child loaded, load third child
  5. and so on

For example I have a parent component app.module.ts with children:

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

and 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?

 }

回答1:


In each of your child components, add an output:

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

and emit an event when you decide that the component is initialized (or loaded, as your question says), and that the next one can thus be displayed:

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

In the parent component, have a counter:

counter = 0;

Increment the counter every time a component is initialized, and don't display a component until the counter is allowing it to be displayed:

<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>



回答2:


Perhaps you mean something like:

<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));
  }
}

If you want to add different components, you can use an approach like Angular 2 dynamic tabs with user-click chosen components



来源:https://stackoverflow.com/questions/46234130/angular-4-load-components-one-by-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!