If you're using SystemJS you can create the element dynamically using document.createElement()
and append using appendChild()
then call System.import()
to initialize the app. This assumes that all necessary application assets and SystemJS configuration has been loaded already:
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 app element is created, appended, and initialized from within the event handler of the button click.
UPDATE If you're using Webpack and depending on your build/bundling process, you can load the main transpiled/bundle JS file dynamically using a pattern in this question to avoid your error. If you're using @angular/cli
this may be more difficult as generated files have identifiers such as main.97e5159ded9c783f627a.bundle.js
.
Hopefully that helps!