Upgrading Components

The only Angular 1.x components that can be upgraded and used in Angular 2 codeare those that strictly follow the component pattern outlined at the top ofthis document. Wherever possible use Angular 1.5+'s .component.

Here is an Angular 1.x directive that conforms to ng-upgrade's "componentdirective" specification:

  1. angular.module('app').directive('a1Upgradable', function a1UpgradableDirective() {
  2. return {
  3. restrict: 'E',
  4. scope: {},
  5. bindToController: {},
  6. controller: Upgradable,
  7. controllerAs: 'a1Upgradable',
  8. template: `<span>{{ a1Upgradable.message }}</span>`
  9. };
  10. });
  11. class Upgradable {
  12. message = 'I am an Angular 1 Directive';
  13. }

Equivalently this can be written using .component in Angular 1.5+:

  1. angular.module('app').component('a1Upgradable', {
  2. controller: Upgradable,
  3. template: `<span>{{ a1Upgradable.message }}</span>`
  4. });
  5. class Upgradable {
  6. message = 'I am an Angular 1 Directive';
  7. }

Below is an Angular 2 component that will use the upgraded Angular 1.xdirective:

  1. import {upgradeAdapter} from '../upgrade-adapter';
  2. import {A2UsingA1Component} from './a2-using-a1.component';
  3. @NgModule({
  4. declarations: [upgradeAdapter.upgradeNg1Component('a1Upgradable'), A2UsingA1Component],
  5. providers: [],
  6. imports: [BrowserModule]
  7. })
  8. export class AppModule {
  9. }
  1. import {Component} from '@angular/core';
  2. @Component({
  3. selector: 'a2-using-a1',
  4. template: `<p>{{ message }}<a1-upgradable></a1-upgradable></p>`
  5. })
  6. export class A2UsingA1Component {
  7. message = 'Angular 2 Using Angular 1: ';
  8. }

Finally, let Angular 1.x know about the directive:

  1. import {a1UpgradableDirective} from './components/a1-upgradable';
  2. // Angular 1 Vendor Import
  3. import * as angular from 'angular';
  4. // Register classic Angular 1 modules
  5. angular
  6. .module(APPNAME)
  7. .directive('a1Upgradable', a1UpgradableDirective)

原文: https://angular-2-training-book.rangle.io/handout/migrate/ng-upgrade/upgrade-component.html