Angular 2 stand alone components

纵然是瞬间 提交于 2019-11-29 08:14:08
yurzui

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

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