Rubén_ic
Rubén_ic

Reputation: 137

How to load an Angular2 app only when a DOM element is present

I have this code, which is working perfectly, on my main.ts file (the bootstrap file for the app):

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';

platformBrowserDynamic().bootstrapModule(AppModule);

But I just want to bootstrap the app when the main selector is there (because if not it raises the classic error of selector not found), so I thought something like the following code would work:

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';

document.addEventListener('DOMContentLoaded', function() {
  var shouldBootstrap = document.getElementById("my-app-selector");
  if (shouldBootstrap) {
    platformBrowserDynamic().bootstrapModule(AppModule);
  }
});

Unfortunately it is not working, I suppose it is due to the combination of javascript and typescript here. Is there a way to listen for an event and also for the presence of a DOM element to prevent the angular2 being bootstrapped when it is not necessary?

I would go for this approach because I serve the javascript bundled with webpack.

Thanks!

Upvotes: 2

Views: 1263

Answers (2)

Yogesh Patel
Yogesh Patel

Reputation: 314

you are using webpack then just add your bundle file after selector tag.

Error my-app selector not found

 <body>
 <script src="../dist/app.bundle.js"></script>
 <my-app>Loading...</my-app>
 </body>

Working

 <body>
 <my-app>Loading...</my-app>
 <script src="../dist/app.bundle.js"></script>
 </body>

Upvotes: 1

Nate May
Nate May

Reputation: 4062

Try to console.log(document.getElementById("my-app-selector")) and see what is returned when the selector is present or not. Then build your if statement on what you might or might not expect:

if (document.getElementById("my-app-selector") !== undefined){
  platformBrowserDynamic().bootstrapModule(AppModule);
}

Or (use let not var in typescript)

let shouldBootstrap = document.getElementById("my-app-selector");

Upvotes: 3

Related Questions