Angular2混合模式:动态加载Ng1组件

时间:2016-07-11 10:15:20

标签: angular ng-upgrade

我正在尝试使用ViewContainerRef.createComponent()在ng2父组件内动态加载ng1组件。这是plunker https://plnkr.co/edit/HADJILztGEELg5lavfvP?p=preview

然而它抛出以下异常:

ViewWrappedException {_wrapperMessage: "Error in ./DynamicComponent class DynamicComponent - inline template:0:27", _originalException: TypeError: Cannot read property 'scope' of null
    at new UpgradeNg1ComponentAdapter (https://npmcd…, _originalStack: "TypeError: Cannot read property 'scope' of null?  …ular/core@2.0.0-rc.2/bundles/core.umd.js:8276:49)", _context: DebugContext, _wrapperStack: "Error: Error in ./DynamicComponent class DynamicCo…DNGqj1u/src/dynViewComponent.ts!transpiled:84:45)"}_context: DebugContext_originalException: TypeError: Cannot read property 'scope' of null

这是ng1-comp.js

define( ['bootstrap'], 
function( ng1 ) {
  'use strict';

    ng1.ngModule.component('ng1Comp', {
      template:'<h1>NG1 Comp </h1>',
    });
} );

这是动态Loader:

@Component({
  selector: 'my-app',
  template: `
    <div>This is dynamic view container</div>
  `
})
export class App {
  private _componentRef: ComponentRef<any>;
  private vcRef:any;  
  constructor(private viewContainerRef: ViewContainerRef, private resolver: 
  ComponentResolver){
      this.vcRef = this.viewContainerRef;
  }

  public ngAfterViewInit(){
    if (this._componentRef) {
        this._componentRef.destroy();
        this._componentRef = null;
    }

    System.import('js/ng1-comp.js');    

    const metadata = new ComponentMetadata({
        directives: [upgradeAdapter.instance.upgradeNg1Component('ng1Comp') ],
        selector: 'dynamic-content',
        template: '<ng1-comp></ng1-comp>'
    });
    this.createComponentFactory(this.resolver, metadata)
      .then(factory => {
        const injector = ReflectiveInjector.fromResolvedProviders([], 
          this.vcRef.parentInjector);
        this.vcRef.createComponent(factory, 0, injector, []);
      });
  }

  private createComponentFactory(resolver: ComponentResolver, 
      metadata: ComponentMetadata): Promise<ComponentFactory<any>> {
    const cmpClass = class DynamicComponent {};
    const decoratedCmp = Component(metadata)(cmpClass);
    return resolver.resolveComponent(decoratedCmp);
  }

}

欣赏任何指示..

1 个答案:

答案 0 :(得分:0)

UpgradeAdapter看起来这是一个问题。它需要在应用程序启动之前完成所有NG1升级。解决方法是升级动态加载的所有NG1组件,以便在调用UpgradeAdapter.bootstrap()之前进行预升级。

问题#9959使用angualr2 github登录。 同时这里是plunker的解决方法。