Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 How to load 2 App root component separately

Tags:

angular

Is it possible to load 2 different root components (not side by side in page). Found a plunker example, only differences is that both of the root component is loaded in a single page.

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

What I want to achieve is that so each of the component have their own layout and not shared with the app.component.

Example: app.component would have a view template for normal users where as admin.component would have dashboard template.

Is this achievable? or I have to create 2 separate project for this?(One for normal view other for dashboard view)

like image 255
penleychan Avatar asked Aug 25 '16 04:08

penleychan


1 Answers

For this purpose a better approach maybe is use NgComponentOutlet directive. In app.component.html only is needed to use:

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

Then in app.component.ts you need to provide the component you want to render at run-time:

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

You maybe can smartly do all your different layout components inherits some base layout component if you want all then have a common functionality.

As example of use you can subscribe to router events in ngOnInit() method:

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

Finally pass the exact layout data component you want for your module in the app-routing.module.ts declaration

enter image description here

like image 109
Sergio Medialdea Avatar answered Oct 13 '22 01:10

Sergio Medialdea