Search code examples
angulartypescriptangular11

How to initialise an empty ComponentRef?


Using Angular 11 and Typescript Strict mode I have:

export class ModalService {

  renderer: Renderer2;
  component?: ComponentRef<any>;
  element: HTMLElement | null;
  modal: HTMLDivElement;

  constructor(private componentFactoryResolver: ComponentFactoryResolver, private application: ApplicationRef, private rendererFactory: RendererFactory2, private popupService: PopupService) { 

    this.renderer = rendererFactory.createRenderer(null, null);
    this.element = new HTMLElement();
    this.modal = new HTMLDivElement();

  }

  open(component: any, data?: any): void {

    if(this.element) 
      return;

    this.renderer.addClass(document.body, 'modal');

    this.popupService.closeAll();

    const injector: Injector = Injector.create({ providers: [{ provide: 'modal', useValue: data }]});

    this.component = this.componentFactoryResolver.resolveComponentFactory(component).create(injector);

    this.component.instance.modal = this;

    this.application.attachView(this.component.hostView);

    this.element = (this.component.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement;

    this.modal = document.createElement('div');

    this.modal.id = 'modal';

    this.modal.appendChild(this.element);

    document.body.appendChild(this.modal);

  }

  close(): void {

    this.application.detachView(this.component.hostView);
    this.modal.parentNode?.removeChild(this.modal);
    this.component?.destroy();
    this.element = null;
    this.renderer.removeClass(document.body, 'modal');

  }

}

I get the error:

Property 'component' has no initializer and is not definitely assigned in the constructor.

What would be the best way to solve this?

Is it possible to initialise an empty ComponentRef?


Solution

  • That could be because of strict mode.

    Can you try with this?

    component!: ComponentRef<any>;
    

    Note the “!” after component.