Search code examples
angularngrx

Angular, createComponent() throws "ERROR TypeError: Cannot add property"


I am creating components dynamically and I am passing the component's class via ngrx action and eventually have:

loadComponent(componentType: Type<any>): void {
  const viewContainerRef = this.contentHost.viewContainerRef;
  viewContainerRef.clear();
  const componentFactory = this.componentFactoryResolver.resolveComponentFactory(componentType);
  const componentRef = viewContainerRef.createComponent(componentFactory);
  componentRef.instance.type = componentType;
}    

As soon as this method is called I get:

core.js:5980 ERROR TypeError: Cannot add property __NG_ELEMENT_ID__, object is not extensible
    at bloomAdd (core.js:3048)
    at diPublicInInjector (core.js:3190)
    at createRootComponentView (core.js:12159)
    at ComponentFactory$1.create (core.js:24822)
    at ViewContainerRef.createComponent (core.js:22896) <--- this is the createComponent()
    at WorkspaceSingleComponent.loadComponent (workspace-single.component.ts:45)  <---- this is my class
    at SafeSubscriber._next (workspace-single.component.ts:32)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:183)
    at SafeSubscriber.next (Subscriber.js:122)
    at Subscriber._next (Subscriber.js:72)

Solution

  • Apparently when this Component class passes thru the ngrx action's serialization it gets frozen and we cannot use it to construct new instances.

    We can use the following workaround to make it working, until we find a better way. In app.module.ts, to your StoreModule's initializer add:

    StoreModule.forRoot(reducers, {
          metaReducers,
          runtimeChecks: {
            strictActionImmutability: false,
            strictActionSerializability: false,
            strictActionTypeUniqueness: isDevMode(),
            strictActionWithinNgZone: isDevMode(),
            strictStateImmutability: isDevMode(),
            strictStateSerializability: false,
          }
        }),
    

    Thanks to Simon Hayden for this workaround. Source: https://gitter.im/ngrx/platform?at=5f3cbaa33dac53434017de6a