Rubén_ic Rubén_ic - 26 days ago 5
Javascript Question

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!

Answer

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");