Instance Angular 2 Component Two times

后端 未结 3 1624
借酒劲吻你
借酒劲吻你 2020-12-03 14:44

I\'m trying to learn Angular 2, so I was making some hello world examples. Here is my code:

boot.ts

import {bootstrap}          


        
3条回答
  •  感情败类
    2020-12-03 15:14

    If you come across this question and really do want two root level app instances, this can be accomplished by manually bootstrapping your root level component(s) in the NgModule ngDoBootstrap method.

    (Note that in Angular 5+ this method may no longer be required, see this Angular PR)

    We first find all root elements we want to bootstrap and give them a unique ID. Then for each instance, hack the component factory selector with the new ID and trigger the bootstrap.

    const entryComponents = [
      RootComponent,
    ];
    
    @NgModule({
      entryComponents,
      imports: [
        BrowserModule,
      ],
      declarations: [
        RootComponent,
      ],
    })
    export class MyModule {
      constructor(private resolver: ComponentFactoryResolver) {}
    
      ngDoBootstrap(appRef: ApplicationRef) {
        entryComponents.forEach((component: any) => {
          const factory = this.resolver.resolveComponentFactory(component);
          let selectorName;
          let elements;
    
          // if selector is a class
          if (factory.selector.startsWith('.')) {
            selectorName = factory.selector.replace(/^\./, '');
            elements = document.getElementsByClassName(selectorName);
    
          // else assume selector is an element
          } else {
            selectorName = factory.selector;
            elements = document.getElementsByTagName(selectorName);
          }
    
          // no elements found, early return
          if (elements.length === 0) {
            return;
          }
    
          // more than one root level componenet found, bootstrap unique instances
          if (elements.length > 1) {
            const originalSelector = factory.selector;
    
            for (let i = 0; i < elements.length; i += 1) {
              elements[i].id = selectorName + '_' + i;
              (factory).factory.selector = '#' + elements[i].id;
              appRef.bootstrap(factory);
            }
    
            (factory).factory.selector = originalSelector;
    
          // only a single root level component found, bootstrap as usual
          } else {
            appRef.bootstrap(factory);
          }
        });
      }
    }
    

    Now, assuming our RootComponent's selector was '.angular-micro-app' this will work as expected:

    
        
    ...

提交回复
热议问题