0

I am trying to load the ng1 components dynamically inside a ng2 parent component using ViewContainerRef.createComponent(). Here is the plunker https://plnkr.co/edit/HADJILztGEELg5lavfvP?p=preview

However it throws following exception:

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

Here is the ng1-comp.js

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

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

Here is the dynamic 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);
  }

}

Appreciate any pointers..

user3869623
  • 2,363
  • 2
  • 15
  • 19

1 Answers1

0

Looks like this is an issue with UpgradeAdapter. It requires all the NG1 upgrades be done before app is bootsrapped. The work around is to upgrade all the NG1 components being loaded dynamically to be pre-upgraded before UpgradeAdapter.bootstrap() is called.

Issue #9959 Logged with angualr2 github. Meantime here is the plunker with workaround.

user3869623
  • 2,363
  • 2
  • 15
  • 19