Search code examples
angularangular2-templateangular2-servicesangular2-directives

Existing website + angular2 integration with optional component


I have existing website and I got angular2 (cli main.js) on it.

I have got it's main <app></app> tag added for main component.

Now I have another component, which is stats component. it will only show if user is logged in.

The problem is, If I don't add <app-stats></app-stats> inside <app></app> component tag, then it wont render it.

How can I make stats component to be bootstrap without tied to main app component? So It can be put anywhere on the html page without being inside <app></app> and also its optional, if user is not logged in, then it be put inside html code.

  1. Freely add <app-stats></app-stats> on html page
  2. <app-stats></app-stats> (optional - will be only added if user is logged in from server side script "php") - I just want to mention it here, because currently if I dont add this tag, then I get error "missing component...."

Solution

  • If you are using Angular RC5, you may bootstrap multiple component and use as suited.

      @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 {}
    

    Here is the Plunker!

    Update

    you may try below for dynamic addition of components in bootstrap array.

    in your app module typescript

    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 {}
    

    Now key is when you are doing System.import('<main file which bootstraps your appmodule>') before that login.js file should have been loaded and value must have been set.

    You may create a Global variable as well to window object which can have login info set, which may be utilized inside AppModule.

    Hope this helps!!