Search code examples
angularjsupgradeng-upgrade

Bootstrap Angular 2 with Angular 1


I have app.js in angular 1.4. app.js contains the following:

var app = angular.module('testingBoot',[...], function(){});

I am making another file : test.ts. This contains the following :

import {bootstrap} from 'angular2/platform/browser';
import {UpgradeAdapter} from 'angular2/upgrade';
import {AppComponent} from './app.component';

const upgradeAdapter = new UpgradeAdapter();
upgradeAdapter.bootstrap(document.body, ['testingBoot']);

Index.html :

<script src="/flat-ui/libs/es6-shim.min.js"></script>
    <script src="/flat-ui/libs/systemjs/dist/system.src.js"></script>
    <script src="/flat-ui/libs/angular2-polyfills.js"></script>
    <script src="/flat-ui/libs/systemjs/dist/system.src.js"></script>
    <script src="/flat-ui/libs/Rx.js"></script>
    <script src="/flat-ui/libs/angular2.dev.js"></script>
<script>
 System.config({
       baseURL : '/',
       defaultJSExtension: true,
       map: {
           mainTest : './flat-ui/js/typeScript',
           angular2 : '/flat-ui/libs/angular2'
       },
        packages: {
          mainTest: {
              format: 'register',
            defaultExtension: 'js'
          },
          angular2 : {
              baseURL : '/flat-ui/libs/angular2',
              defaultExtension: 'js'
          }
        }
      });
 System.import('mainTest/test')
      .then(null, console.error.bind(console));
</script>
<script type="text/javascript" src="/flat/js/app.js"></script>

Till this all works fine and the angular 1 app bootstraps well.

Now the issue is that I need to include a component created in Angular 2 into Angular 1 as a directive.

The docs say that all I need to write is :

angular.module('testingBoot').directive('testingOnActivity', upgradeAdapter.downgradeNg2Component(AppComponent));

But where and in which file do I include this? If I include this in test.ts then I get the error that angular is not defined and I cannot include this in app.js as then upgradeAdapter is not present and app.js


Solution

  • You can include it between:

    const upgradeAdapter = new UpgradeAdapter();
    upgradeAdapter.bootstrap(document.body, ['testingBoot']);
    

    my boot.ts:

    import {UpgradeAdapter} from 'angular2/upgrade';
    import {bootstrap}    from 'angular2/platform/browser'
    import {AppComponent} from './app.component'
    
    declare var angular:any;
    
    export const upgradeAdapter = new UpgradeAdapter();
    myApp.directive('testDirective', upgradeAdapter.downgradeNg2Component(AppComponent));
    
    upgradeAdapter.bootstrap(document.body, ['myApp']);