现有网站 + angular2 与可选组件的集成

Existing website + angular2 integration with optional component

我有现成的网站,上面有 angular2 (cli main.js)。

我已经为主要组件添加了主要 <app></app> 标签。

现在我有另一个组件,它是统计组件。它只会在用户登录时显示。

问题是,如果我不在 <app></app> 组件标签内添加 <app-stats></app-stats>,它就不会呈现它。

如何使统计组件成为 bootstrap 而不绑定到主应用程序组件?所以它可以放在 html 页面的任何地方而不是在 <app></app> 里面,而且它也是可选的,如果用户没有登录,那么它会放在 html 代码里面。

  1. 在 html 页上自由添加 <app-stats></app-stats>
  2. <app-stats></app-stats>(可选 - 仅当用户从服务器端脚本 "php" 登录时才添加) - 我只想在这里提及它,因为目前如果我不添加此标签,然后我得到错误 "missing component...."

如果您正在使用 Angular RC5,您可以 bootstrap 多个组件并根据需要使用。

  @Component({
    selector: 'app',
    template: `app`,
  })
  export class App {
    constructor() {}
  }

  @Component({
    selector: 'app-status',
    template: `app-status`,
  })
  export class AppStatus {
   constructor() {}
  }

  @NgModule({
   imports: [ BrowserModule ],
   declarations: [ App ],
   bootstrap: [ App, AppStatus ]
  })
  export class AppModule {}

这是Plunker!

更新

您可以在下面尝试在 bootstrap 数组中动态添加组件。

在您的应用模块打字稿中

let login = require('login.js');

let bootstrapcomponents = [];

if(login.isLoggedIn){
  bootstrapcomponents = [AppComponent, AppStatsComponent]
}
else{
 bootstrapcomponents = [AppComponent]
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: bootstrapcomponents 
})
export class AppModule {}

现在的关键是当你在做 System.import('<main file which bootstraps your appmodule>') 之前 login.js 文件应该已经加载并且值必须已经设置。

您也可以为 window 对象创建一个全局变量,它可以设置登录信息,可以在 AppModule 中使用。

希望对您有所帮助!!