How can I manually initialize angular 2/4 app

I need to initialize my angular app using my-app component, the problem is that this component exists in the html template that does not load when the page starts, so I need to manually initialize, otherwise it gives me an error: Error: selector "my-app" did not match elements

Is it possible?

+3


source to share


2 answers


If you are using SystemJS you can dynamically create an element with document.createElement()

and add with appendChild()

and then call System.import()

to initialize the application. This assumes that all the required application resources and SystemJS configuration are already loaded:

Html

<body>
  <div id="app"></div>

  <button type="button" id="foo">Click Me</button>

  <script src="app.js"></script>
</body>

      

Js



(function() {
  var button = document.getElementById('foo');
  var container = document.getElementById('app');

  button.addEventListener('click', function() {
    var myApp = document.createElement('my-app');
    myApp.textContent = 'Loading...';

    container.appendChild(myApp);

    System.import('app')
      .catch(console.error.bind(console));
  });
})();

      

Here is a plunker demonstrating the functionality. The application element is created, added, and initialized from the button click event handler.

UPDATE . If you are using Webpack and depending on your build / bundling process you can dynamically load the main JS file with the extension / bundle using the template in this question to avoid the error. If you are using @angular/cli

it can be trickier as the generated files have IDs like main.97e5159ded9c783f627a.bundle.js

.

Hope this helps!

+2


source


Here's how you can do it. First, create your application root module and declare your root component in declarations

and entryComponents

. Do not add to ingredients bootstrap

. Then define a method ngDoBootstrap

in the module class so that Angular knows that you will load the app yourself. Inside this method, get the reference to ApplicationRef

, and then when the time is right bootstrap

, just call that passed the reference of the class AppComponent

. Here is the code:

@NgModule({
  imports: [BrowserModule],
  declarations: [AppComponent],
  entryComponents: [AppComponent]
})
export class AppModule {
  ngDoBootstrap(app: ApplicationRef) {
    // delay bootstrap by 3 seconds
    setTimeout(() => {
      app.bootstrap(AppComponent)
    }, 3000);
  }
}

      



Essentially this is what Angular does under the hood when you call bootstrapModule(AppModule);

with the above boostrapComponents

.

Read How to manually download an Angular app for more details.

+1


source







All Articles