{ "id": "guide/upgrade-performance", "title": "Upgrading for performance", "contents": "\n\n\n
\n mode_edit\n
\n\n\n
\n

Upgrading for performancelink

\n
\n

Angular is the name for the Angular of today and tomorrow.
\nAngularJS is the name for all 1.x versions of Angular.

\n
\n

This guide describes some of the built-in tools for efficiently migrating AngularJS projects over to\nthe Angular platform, one piece at a time. It is very similar to\nUpgrading from AngularJS with the exception that this one uses the downgradeModule() helper function instead of the UpgradeModule class. This affects how the app is bootstrapped and how change detection is\npropagated between the two frameworks. It allows you to upgrade incrementally while improving the\nspeed of your hybrid apps and leveraging the latest of Angular in AngularJS apps early in the\nprocess of upgrading.

\n

Preparationlink

\n

Before discussing how you can use downgradeModule() to create hybrid apps, there are things that\nyou can do to ease the upgrade process even before you begin upgrading. Because the steps are the\nsame regardless of how you upgrade, refer to the Preparation section of\nUpgrading from AngularJS.

\n

Upgrading with ngUpgradelink

\n

With the ngUpgrade library in Angular you can upgrade an existing AngularJS app incrementally by\nbuilding a hybrid app where you can run both frameworks side-by-side. In these hybrid apps you can\nmix and match AngularJS and Angular components and services and have them interoperate seamlessly.\nThat means you don't have to do the upgrade work all at once as there is a natural coexistence\nbetween the two frameworks during the transition period.

\n

How ngUpgrade Workslink

\n

Regardless of whether you choose downgradeModule() or UpgradeModule, the basic principles of\nupgrading, the mental model behind hybrid apps, and how you use the upgrade/static utilities remain the same. For more information, see the\nHow ngUpgrade Works section of\nUpgrading from AngularJS.

\n
\n

The Change Detection section of\nUpgrading from AngularJS only applies to apps that use UpgradeModule. Though\nyou handle change detection differently with downgradeModule(), which is the focus of this\nguide, reading the Change Detection section provides helpful\ncontext for what follows.

\n
\n

Change Detection with downgradeModule()link

\n

As mentioned before, one of the key differences between downgradeModule() and UpgradeModule has\nto do with change detection and how it is propagated between the two frameworks.

\n

With UpgradeModule, the two change detection systems are tied together more tightly. Whenever\nsomething happens in the AngularJS part of the app, change detection is automatically triggered on\nthe Angular part and vice versa. This is convenient as it ensures that neither framework misses an\nimportant change. Most of the time, though, these extra change detection runs are unnecessary.

\n

downgradeModule(), on the other side, avoids explicitly triggering change detection unless it\nknows the other part of the app is interested in the changes. For example, if a downgraded component\ndefines an @Input(), chances are that the app needs to be aware when that value changes. Thus,\ndowngradeComponent() automatically triggers change detection on that component.

\n

In most cases, though, the changes made locally in a particular component are of no interest to the\nrest of the app. For example, if the user clicks a button that submits a form, the component usually\nhandles the result of this action. That being said, there are cases where you want to propagate\nchanges to some other part of the app that may be controlled by the other framework. In such cases,\nyou are responsible for notifying the interested parties by manually triggering change detection.

\n

If you want a particular piece of code to trigger change detection in the AngularJS part of the app,\nyou need to wrap it in\nscope.$apply(). Similarly, for\ntriggering change detection in Angular you would use ngZone.run().

\n

In many cases, a few extra change detection runs may not matter much. However, on larger or\nchange-detection-heavy apps they can have a noticeable impact. By giving you more fine-grained\ncontrol over the change detection propagation, downgradeModule() allows you to achieve better\nperformance for your hybrid apps.

\n

Using downgradeModule()link

\n

Both AngularJS and Angular have their own concept of modules to help organize an app into cohesive\nblocks of functionality.

\n

Their details are quite different in architecture and implementation. In AngularJS, you create a\nmodule by specifying its name and dependencies with\nangular.module(). Then you can add\nassets using its various methods. In Angular, you create a class adorned with an NgModule decorator that describes assets in metadata.

\n

In a hybrid app you run both frameworks at the same time. This means that you need at least one\nmodule each from both AngularJS and Angular.

\n

For the most part, you specify the modules in the same way you would for a regular app. Then, you\nuse the upgrade/static helpers to let the two frameworks know about assets they can use from each\nother. This is known as \"upgrading\" and \"downgrading\".

\n
\n

Definitions:

\n\n
\n

An important part of inter-linking dependencies is linking the two main modules together. This is\nwhere downgradeModule() comes in. Use it to create an AngularJS module—one that you can use\nas a dependency in your main AngularJS module—that will bootstrap your main Angular module and\nkick off the Angular part of the hybrid app. In a sense, it \"downgrades\" an Angular module to an\nAngularJS module.

\n

There are a few things to note, though:

\n
    \n
  1. \n

    You don't pass the Angular module directly to downgradeModule(). All downgradeModule() needs\nis a \"recipe\", for example, a factory function, to create an instance for your module.

    \n
  2. \n
  3. \n

    The Angular module is not instantiated until the app actually needs it.

    \n
  4. \n
\n

The following is an example of how you can use downgradeModule() to link the two modules.

\n\n// Import `downgradeModule()`.\nimport { downgradeModule } from '@angular/upgrade/static';\n\n// Use it to downgrade the Angular module to an AngularJS module.\nconst downgradedModule = downgradeModule(MainAngularModuleFactory);\n\n// Use the downgraded module as a dependency to the main AngularJS module.\nangular.module('mainAngularJsModule', [\n downgradedModule\n]);\n\n

Specifying a factory for the Angular modulelink

\n

As mentioned earlier, downgradeModule() needs to know how to instantiate the Angular module. It\nneeds a recipe. You define that recipe by providing a factory function that can create an instance\nof the Angular module. downgradeModule() accepts two types of factory functions:

\n
    \n
  1. NgModuleFactory
  2. \n
  3. (extraProviders: StaticProvider[]) => Promise<NgModuleRef>
  4. \n
\n

When you pass an NgModuleFactory, downgradeModule() uses it to instantiate the module using\nplatformBrowser's bootstrapModuleFactory(), which is compatible with ahead-of-time (AOT) compilation. AOT compilation\nhelps make your apps load faster. For more about AOT and how to create an NgModuleFactory, see the\nAhead-of-Time Compilation guide.

\n

Alternatively, you can pass a plain function, which is expected to return a promise resolving to an\nNgModuleRef (i.e. an instance of your Angular module). The function is called\nwith an array of extra Providers that are expected to be available on the\nreturned NgModuleRef's Injector. For example, if you are using platformBrowser or platformBrowserDynamic, you can\npass the extraProviders array to them:

\n\nconst bootstrapFn = (extraProviders: StaticProvider[]) => {\n const platformRef = platformBrowserDynamic(extraProviders);\n return platformRef.bootstrapModule(MainAngularModule);\n};\n// or\nconst bootstrapFn = (extraProviders: StaticProvider[]) => {\n const platformRef = platformBrowser(extraProviders);\n return platformRef.bootstrapModuleFactory(MainAngularModuleFactory);\n};\n\n

Using an NgModuleFactory requires less boilerplate and is a good default option as it supports AOT\nout-of-the-box. Using a custom function requires slightly more code, but gives you greater\nflexibility.

\n

Instantiating the Angular module on-demandlink

\n

Another key difference between downgradeModule() and UpgradeModule is that the latter requires\nyou to instantiate both the AngularJS and Angular modules up-front. This means that you have to pay\nthe cost of instantiating the Angular part of the app, even if you don't use any Angular assets\nuntil later. downgradeModule() is again less aggressive. It will only instantiate the Angular part\nwhen it is required for the first time; that is, as soon as it needs to create a downgraded\ncomponent.

\n

You could go a step further and not even download the code for the Angular part of the app to the\nuser's browser until it is needed. This is especially useful when you use Angular on parts of the\nhybrid app that are not necessary for the initial rendering or that the user doesn't reach.

\n

A few examples are:

\n\n

Bootstrapping with downgradeModule()link

\n

As you might have guessed, you don't need to change anything in the way you bootstrap your existing\nAngularJS app. Unlike UpgradeModule—which requires some extra steps—\ndowngradeModule() is able to take care of bootstrapping the Angular module, as long as you provide\nthe recipe.

\n

In order to start using any upgrade/static APIs, you still need to load the Angular framework as\nyou would in a normal Angular app. You can see how this can be done with SystemJS by following the\ninstructions in the Upgrade Setup guide, selectively copying code from the\nQuickStart github repository.

\n

You also need to install the @angular/upgrade package via npm install @angular/upgrade --save\nand add a mapping for the @angular/upgrade/static package:

\n\n'@angular/upgrade/static': 'npm:@angular/upgrade/bundles/upgrade-static.umd.js',\n\n

Next, create an app.module.ts file and add the following NgModule class:

\n\nimport { NgModule } from '@angular/core';\nimport { BrowserModule } from '@angular/platform-browser';\n\n@NgModule({\n imports: [\n BrowserModule\n ]\n})\nexport class MainAngularModule {\n // Empty placeholder method to satisfy the `Compiler`.\n ngDoBootstrap() {}\n}\n\n

This bare minimum NgModule imports BrowserModule, the module every Angular browser-based app\nmust have. It also defines an empty ngDoBootstrap() method, to prevent the Compiler from returning errors. This is necessary because the module will not have a bootstrap\ndeclaration on its NgModule decorator.

\n
\n

You do not add a bootstrap declaration to the NgModule decorator since AngularJS owns the root\ntemplate of the app and ngUpgrade bootstraps the necessary components.

\n
\n

You can now link the AngularJS and Angular modules together using downgradeModule().

\n\nimport { platformBrowserDynamic } from '@angular/platform-browser-dynamic';\nimport { downgradeModule } from '@angular/upgrade/static';\n\nconst bootstrapFn = (extraProviders: StaticProvider[]) => {\n const platformRef = platformBrowserDynamic(extraProviders);\n return platformRef.bootstrapModule(MainAngularModule);\n};\nconst downgradedModule = downgradeModule(bootstrapFn);\n\nangular.module('mainAngularJsModule', [\n downgradedModule\n]);\n\n

The existing AngularJS code works as before and you are ready to start adding Angular code.

\n

Using Components and Injectableslink

\n

The differences between downgradeModule() and UpgradeModule end here. The rest of the\nupgrade/static APIs and concepts work in the exact same way for both types of hybrid apps.\nSee Upgrading from AngularJS to learn about:

\n\n
\n

While it is possible to downgrade injectables, downgraded injectables will not be available until\nthe Angular module that provides them is instantiated. In order to be safe, you need to ensure\nthat the downgraded injectables are not used anywhere outside the part of the app where it is\nguaranteed that their module has been instantiated.

\n

For example, it is OK to use a downgraded service in an upgraded component that is only used\nfrom a downgraded Angular component provided by the same Angular module as the injectable, but it\nis not OK to use it in an AngularJS component that may be used independently of Angular or use\nit in a downgraded Angular component from a different module.

\n
\n

Using ahead-of-time compilation with hybrid appslink

\n

You can take advantage of ahead-of-time (AOT) compilation in hybrid apps just like in any other\nAngular app. The setup for a hybrid app is mostly the same as described in the\nAhead-of-Time Compilation guide save for differences in index.html and\nmain-aot.ts.

\n

AOT needs to load any AngularJS files that are in the <script> tags in the AngularJS index.html.\nAn easy way to copy them is to add each to the copy-dist-files.js file.

\n

You also need to pass the generated MainAngularModuleFactory to downgradeModule() instead of the\ncustom bootstrap function:

\n\nimport { downgradeModule } from '@angular/upgrade/static';\nimport { MainAngularModuleNgFactory } from '../aot/app/app.module.ngfactory';\n\nconst downgradedModule = downgradeModule(MainAngularModuleNgFactory);\n\nangular.module('mainAngularJsModule', [\n downgradedModule\n]);\n\n

And that is all you need to do to get the full benefit of AOT for hybrid Angular apps.

\n

Conclusionlink

\n

This page covered how to use the upgrade/static package to incrementally\nupgrade existing AngularJS apps at your own pace and without impeding further development of the app\nfor the duration of the upgrade process.

\n

Specifically, this guide showed how you can achieve better performance and greater flexibility in\nyour hybrid apps by using downgradeModule() instead of UpgradeModule.

\n

To summarize, the key differentiating factors of downgradeModule() are:

\n
    \n
  1. It allows instantiating or even loading the Angular part lazily, which improves the initial\nloading time. In some cases this may waive the cost of running a second framework altogether.
  2. \n
  3. It improves performance by avoiding unnecessary change detection runs while giving the developer\ngreater ability to customize.
  4. \n
  5. It does not require you to change how you bootstrap your AngularJS app.
  6. \n
\n

Using downgradeModule() is a good option for hybrid apps when you want to keep the AngularJS and\nAngular parts less coupled. You can still mix and match components and services from both\nframeworks, but you might need to manually propagate change detection. In return,\ndowngradeModule() offers more control and better performance.

\n\n \n
\n\n\n" }