Transcluding Angular 2 Components into Angular 1 Directives

Angular 2 components can be transcluded into Angular 1.x directives.

Here is a very simple Angular 2 component:

  1. import {Component} from '@angular/core';
  2. @Component ({
  3. selector: 'a2-transclusion-contents',
  4. template: `<p>{{ message }}</p>`
  5. })
  6. export class A2Transclusion {
  7. message =
  8. 'I am an Angular 2 Component "transcluded" into Angular 1.x';
  9. }

Here is an Angular 1.x directive that supports transclusion:

  1. export function a1TransclusionDirective() {
  2. return {
  3. restrict: 'E',
  4. transclude: true,
  5. scope: {},
  6. bindToController: {},
  7. controller: A1Transclusion,
  8. controllerAs: 'a1ProjectionContents',
  9. template: `
  10. <p>
  11. <ng-transclude></ng-transclude>
  12. </p>
  13. `
  14. };
  15. }
  16. class A1Transclusion {
  17. }

Angular 1.x needs to know about both the component and the directive:

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

Finally, Angular 2 content can be transcluded into Angular 1.x like so:

  1. <a1-transclude>
  2. <a2-transclusion-contents></a2-transclusion-contents>
  3. </a1-transclude>

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