Angular5: loading dynamic components - StaticInjector bug with @ angular / core bindings

I am porting an electronic application from AngularJS to Angular5, and I encounter problems in the part where I need to load an arbitrary module with its components and dynamically convert the main component to a view (this is an add-on system). In my application, the add-on is an angular5 module containing the component that appears in my application with an angular expression.

I dynamically load the component as follows:

@ViewChild("view", { read: ViewContainerRef })
view: ViewContainerRef;

constructor(
  // ...
  private compiler: Compiler,
  private injector: Injector,
  private moduleRef: NgModuleRef<any>
) {}

then

const addonModule = addonObject.getModule();
this.compiler
  .compileModuleAndAllComponentsAsync(addonModule)
  .then(factories => {
    const factory = factories.componentFactories.find(
      componentFactory =>
        addonObject.getViewComponent().name ==
        componentFactory.componentType.name
    );
    if (factory) {
      const cmpRef = factory.create(this.injector, [], null, this.moduleRef);
      cmpRef.instance.config = {
        from: "afd@test.com",
        apikey: "dsfkjd"
      };
      this.view.insert(cmpRef.hostView);
    }
  });

It works fine, but when I add Material Component to the template, it fails when factory.create()with this error:

template:

<div>
    <button mat-button>test</button>
</div>

Error:

ERROR Error: Uncaught (in promise): Error: StaticInjectorError[Renderer2]: 
  StaticInjectorError[Renderer2]: 
    NullInjectorError: No provider for Renderer2!

or

template:

<div fxLayout="row" fxFlex>
    test
</div>

Error:

ERROR Error: Uncaught (in promise): Error: StaticInjectorError[MediaMonitor]: 
  StaticInjectorError[MediaMonitor]: 
    NullInjectorError: No provider for MediaMonitor!

, , addon else, . : (, <button mat-button></button> - <button></button> ) ( <mat-card>test<mat-card> throws Error: Template parse errors: 'mat-card' is not a known element...)

: tsc/ngc/ng-packagr/webpack.

, () NgModule , ng-cli.

- , /, , , fxFlex/mat-button/mat-card?

EDIT: SystemJS : https://github.com/thyb/repro-dynamic-loading

Angular: 5.0.2

Angular : 5.0.0-rc1

+4
1

@yurzui , @ angular/* . - window @angular (@angular/core, @angular/common, @angular/material).

index.html:

window.angular = {
    core: require("@angular/core"),
    common: require("@angular/common"),
    material: require("@angular/material"),
    ...
}

:

const NgModule = (window as any).angular.core.NgModule;
const CommonModule = (window as any).angular.common.CommonModule;
const MatButtonModule = (window as any).angular.material.MatButtonModule;
...

( ), , , ... - , :)

Gitter @ angular/element, , / -, , - https://www.youtube.com/watch?v=ljsOPm4MMEo&feature=youtu.be&t=13m20s. , , : https://github.com/angular/angular/pull/19469

+2

Source: https://habr.com/ru/post/1683278/


All Articles