Angular 2如何分别加载2个App根组件

时间:2016-08-25 04:31:55

标签: angular

是否可以加载2个不同的根组件(不在页面中并排)。 找到plunker example,唯一的区别是两个根组件都加载到一个页面中。

<body>
  <my-app>Loading...</my-app>
  <my-sec>Loading...</my-sec>
</body>

我想要实现的是,每个组件都有自己的布局,不与app.component共享。

示例:app.component将拥有普通用户的视图模板,其中admin.component将具有仪表板模板。

这可以实现吗?或者我必须为此创建2个单独的项目?(一个用于普通视图,另一个用于仪表板视图)

2 个答案:

答案 0 :(得分:1)

虽然我无法找出正确的答案,但这是我在玩了几天之后想出来的。这是&#34;一些什么&#34;足以满足我的需求。

这是我在github上所做的示例的链接。

基本上我决定放弃分别加载2个根组件并动态加载组件的想法。

如果可以进行任何改进,请告诉我。

答案 1 :(得分:0)

为此,更好的方法可能是使用NgComponentOutlet指令。仅在app.component.html中需要使用:

<ng-container *ngComponentOutlet="appLayoutComponent"></ng-container>

然后在app.component.ts中,您需要提供要在运行时呈现的组件:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  public appLayoutComponent: BaseLayoutComponent;

如果您希望所有不同的布局组件都具有共同的功能,那么您可以聪明地继承所有基本布局组件。

作为使用示例,您可以在ngOnInit()方法中订阅路由器事件:

ngOnInit() {
    this.router.events.subscribe((data) => {
      if (data instanceof RoutesRecognized) {
        this.appLayoutComponent = data.state?.root?.firstChild?.data?.layout;
      }
    });
  }

最后在app-routing.module.ts声明中传递所需的确切布局数据组件

enter image description here