Search code examples
angularecmascript-5

How to bootstrap an angular2 component from ES5?


I have a vanilla ES5 script where I am trying to create an angular2 component at runtime and bootstrap it like so,

var mycomp = require('complibrary').mycomponent;
document.addEventListener('DOMContentLoaded', function() {
ng.platformBrowserDynamic.bootstrap(mycomp);
});

Consider complibrary is a separate angular2 component library that we have internally developed. mycomponent is one of the components that we have exported to be consumed by ES5 code. We are using rollup to spit out the final umd definition of our components. An excerpt of mycomponent can be seen below.

var mycomponent = (function () {
function mycomponent() {
    this.name = "Abhang Rane";
}
mycomponent = __decorate([
    _angular_core.Component({
        selector: 'mycomponent',
        template: '<h1>{{name}}</h1>'
    }),
    __metadata('design:paramtypes', [])
], mycomponent);
return mycomponent;
}());

This worked with angular 2.0.0.rc1, but with angular 2.2 and beyond there is no bootstrap method available on platformBrowserDynamic. Is there any way to achieve this with the latest angular 2 build? Preferrably without changing mycomponent...


Solution

  • Angular modules were introduced in Angular 2.0.0 RC5 as a direct successor of AngularJS modules.

    As it's shown in this ES5 example, it is:

    platformBrowserDynamic().bootstrapModule(AppModule);
    

    And the component that is supposed to be bootstrapped should have a respective module defined:

    var AppModule = NgModule({
      declarations: [AppComponent],
      bootstrap: [AppComponent]
    })
    .Class({ constructor: function () {} });