Angular 2 stand alone components

后端 未结 1 1078
情话喂你
情话喂你 2020-12-18 12:37

Just moved over to Angular 2 recently and i am just trying to get my head around pretty much all of it.

I need to build and that just uses stand-alone components, I

相关标签:
1条回答
  • 2020-12-18 13:02

    You can omit the bootstrap option and implementing ngDoBootstrap() yourself. And to conditionally bootstrap components, just do a querySelector before calling appRef.bootstrap(SomeComponent); to check whether the component is already on the page.

    @NgModule({
      imports:      [ BrowserModule ],
      declarations: [ ComponentOne, ComponentTwo ],
      entryComponents: [ ComponentOne, ComponentTwo ]
    })
    export class AppModule { 
      ngDoBootstrap(appRef: ApplicationRef) {
        if(document.querySelector('component-one')) {
          appRef.bootstrap(ComponentOne);
        }
        if(document.querySelector('component-two')) {
          appRef.bootstrap(ComponentTwo);
        }
      }
    }
    

    Note: entryComponents option is required

    Finally in your index.html you can omit second tag and angular won't raise error:

    <body>
      <component-one></component-one>
    </body>
    

    Plunker Example

    If you don't want to see message Angular 2 is running in the development mode. Call enableProdMode() to enable the production mode. you can just enable prod mode or use the following (Since 2.3.0) which is similar as above (i recommend to use the first solution):

    @NgModule({
      imports:      [ BrowserModule ],
      declarations: [ ComponentOne, ComponentTwo ],
      entryComponents: [ComponentOne, ComponentTwo]
    })
    export class AppModule { 
      constructor(private resolver: ComponentFactoryResolver, private inj: Injector) {}
    
      ngDoBootstrap(appRef: ApplicationRef) {   
        if(document.querySelector('component-one')) {
          const compFactory = this.resolver.resolveComponentFactory(ComponentOne);
          let compOneRef = compFactory.create(this.inj, [], 'component-one');
          appRef.attachView(compOneRef.hostView);
          compOneRef.onDestroy(() => {
            appRef.detachView(compOneRef.hostView);
          });
        }
        if(document.querySelector('component-two')) {
          const compFactory = this.resolver.resolveComponentFactory(ComponentTwo);
          let compTwoRef = compFactory.create(this.inj, [], 'component-one');
          appRef.attachView(compTwoRef.hostView);
          compTwoRef.onDestroy(() => {
            appRef.detachView(compTwoRef.hostView);
          });
        }
    
        appRef.tick();
      }
    }
    

    It's just the same that angular does internally when bootstraping component

    Plunker Example

    See also

    • https://github.com/angular/angular/issues/11730
    • Angular2 - Component into dynamicaly created element
    0 讨论(0)
提交回复
热议问题