Projecting Angular 1 Content into Angular 2 Components

In Angular 2 the concept of "transclusion" has been replaced by the concept ofprojection. ng-upgrade provides mechanisms for projecting/transcludingAngular 1.x content into Angular 2 components:

This is what a simple Angular 2 component that supports projection looks like:

  1. import {Component, Input} from '@angular/core';
  2. @Component({
  3. selector: 'a2-projection',
  4. template: `
  5. <p>
  6. Angular 2 Outer Component (Top)
  7. <ng-content></ng-content>
  8. Angular 2 Outer Component (Bottom)
  9. </p>
  10. `
  11. })
  12. export class A2Projection { }

Here's a very simple Angular 1.x directive that will be projected into theAngular 2 component:

  1. export function a1ProjectionContentsDirective() {
  2. return {
  3. restrict: 'E',
  4. scope: {},
  5. bindToController: {},
  6. controller: A1ProjectionContents,
  7. controllerAs: 'a1ProjectionContents',
  8. template: `<p>{{ a1ProjectionContents.message }}</p>`
  9. };
  10. }
  11. class A1ProjectionContents {
  12. message = 'I am an Angular 1 Directive "projected" into Angular 2';
  13. }

Both the component and the directive must be registered with Angular 1.x:

  1. import {A2Projection} from './components/a2-projection';
  2. import {a1ProjectionContentsDirective} from
  3. './components/a1-projection-contents';
  4. // Angular 1 Vendor Import
  5. import * as angular from 'angular';
  6. // Import the upgradeAdapter singleton
  7. import {upgradeAdapter} from './upgrade-adapter';
  8. // Name the application
  9. const APPNAME = 'angular-upgrade-example';
  10. // Register classic Angular 1 modules
  11. angular
  12. .module(APPNAME)
  13. .directive('a2Projection',
  14. upgradeAdapter.downgradeNg2Component(A2Projection))
  15. .directive('a1ProjectionContent', a1ProjectionContentsDirective);

Finally, using the HTML selectors is as simple as:

  1. <a2-projection>
  2. <a1-projection-content></a1-projection-content>
  3. </a2-projection>

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