Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

angular5 - Angular 5: Lazy-loading of component without routing

In my web application I have a "Terms and Conditions" popup that opens by link click in the footer (so it's a core component). Popup comprises of several tabs, each of them is a pretty big template file.

I wonder if it's possible to move tab templates to separate chunk and organize their lazy-loading? I'm not sure if default Angular lazy-loading is acceptable for me because I don't want to have separate route for the popup.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can wait for the user to click on the link and as soon as Click Event occurs, load the required component in the view. Things to keep in mind:

  1. You need to have a placeholder defined for the component in the view.
  2. The terms and conditions component needs to be defined as Entry level component for it's Module or the module where it is used.

     entryComponents: [
        ChildComponent
      ],
    
  3. Make sure to refer to the placeholder in your component and attach the terms and condition component dynamically.

      <div>
          <ng-template #viewContainerRef></ng-template>
       </div>
    

and

@ViewChild('viewContainerRef', { read: ViewContainerRef }) VCR: ViewContainerRef;

and create the component dynamically:

createComponent() {

    let componentFactory = this.CFR.resolveComponentFactory(ChildComponent);
    let componentRef: ComponentRef<ChildComponent> = this.VCR.createComponent(componentFactory);
    let currentComponent = componentRef.instance;

    currentComponent.selfRef = currentComponent;
  // to track the added component, you can reuse this index to remove it later
    currentComponent.index = ++this.index; 

    // providing parent Component reference to get access to parent class methods
    currentComponent.compInteraction = this;

}

there is an example for you here: https://add-or-remove-dynamic-component-parent-child.stackblitz.io


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...