Ok, so you have an Angular1 application, but you want to start building Angular2 components to use within the application. Nothing like getting ahead of the upgrade game, right? Well, follow the steps below and you’ll see that it’s not as hard as it might at first seem!
First, let me show you my project structure (this example is short and sweet – it’s not meant to be representative of a production app from a code organization perspective!). I’ve stripped away everything I could from the example to make sure the focus was solely on making Angular2 components work inside an Angular1 application.
Inside my app folder, first of all I have my angularv1 code.
All this code is doing is creating my app module and adding a controller to it. However, do note that I’m injecting a module called ‘a2’ into the app. More on this in a sec.
AngularV2 component code
Next, I have a basic AngularV2 component that is going to do nothing but accept a person object as an input and display a simple message using the first and last name of the person.
Using UpgradeAdapter to use Angular2 component from Angular1
Finally, the upgrade.ts file has the code that adds the V2 component to an Angular1 module called a2 that can then be injected into my Angular1 app, as shown above when creating my Angular1 module.
Bootstrapping your Angular1 app
Note that you can’t use ng-app to bootstrap your Angular1 application when using Angular2 alongside it. Instead, you have to use the upgrade adapter’s bootstrap method. This ensures that the Angular2 components are loaded along with the Angular1 application.
The index.html page
Setting up your index.html file is actually pretty simple. First, load the Angular1 libraries and the Angular1 code file. Next, load the Angular2 modules.
Note that I’m using SystemJs, so I import the app package which in turn causes my upgrade.ts file to load.
Finally, inside my Angular1 ng-controller directive which loads my V1Controller, I display the person properties, but I also load the Angular2 component and pass the person object to it as well. Note that there is no ng-app directive. As mentioned above, the upgrade adapter’s bootstrap method takes care of loading the Angular1 app.
And, it works! Here’s a screenshot.
For reference, here’s my systemjs.config.js file
And here’s my package.json file. Note I’m using npm rather than bower to install the necessary server and client libraries for my example.
That’s all, folks
So there you go. Without too much effort you can start writing Angular2 components and using them in your existing Angular1 app!