Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to embed a self-contained Angular 2 application inside of an Angular 1 application

Note: I am NOT upgrading an ng1 app. I'm trying to get an ng1 and ng2 app to live side-by-side (or rather nested).

We have roughly the following html showing how we are trying to use two frameworks on the page at once:

  • Angular 1: The whole page is controlled by Angular 1. But we have used ng-non-bindable to tell the ng1 application to ignore the div in the middle of the page.
  • Angular 2: Just the element in the middle of the page should be bootstrapped as Angular 2.

<html ng-app="app">
  <head></head>
  <body ng-controller="appController">
    <header>Angular 1 Stuff</header>

    <div ng-non-bindable>
      <ng2-app></ng2-app>
      <script src="bundle.js"/>
      <!-- bundle.js is the output from webpack and should bootstrap <ng2-app> -->
    </div>

    <footer>Angular 1 Stuff</footer>
  </body>
</html>

Our app works just fine when we run it on its own without trying to integrate into this ng1 application page.

When we run it after integration however, we are getting an error saying there is a conflict with the global require method.

  • The ng1 application is using requirejs
  • The ng2 bundle is the typical output from webpack (using typescript-loader)

Both requirejs and webpack use require but in different contexts.

How can I resolve the conflict?

If you are curious why we do it this way: We are trying to bootstrap a new app on a page that also has an Angular 1 app. Our company has the global header/footer and the content of every page as a separate deployed applications. This allows teams to work on pages as stand-alone projects. One team wants to try and use Angular 2 for their new application on one of our new pages.

like image 344
Tim Kindberg Avatar asked Oct 31 '22 11:10

Tim Kindberg


1 Answers

This question itself can raise thousand of other questions.It is not at all easy to answer this question so fully because you are talking about two major MVC based architectures(Angular1 and Angular2) together.

See how to use angular2 within angular1. Successfully I can bootstrap angular2 app within angular1 app.

It is extremely important to know how you have implemented your angular1 architecture. But if you are angular1&2 guy, you'd probably find ways on your own.

Angular2 App within Angular1 App

Index.html

<body ng-app="app" ng-controller="appController">
    <header>{{myValue}}</header>   //belongs to angular1

    <div ng-non-bindable>
      <my-app></my-app>

      <!-- angular 2 app bootstrapping -->
    </div>

    <footer>Angular 1 Stuff</footer>

    <script>
        var app=angular.module("app",[]);

        app.controller("appController",function($scope){
          $scope.myValue="Nyks";
        })
    </script>
like image 160
Nikhil Shah Avatar answered Nov 08 '22 05:11

Nikhil Shah