如何初始化一个空的 ComponentRef?

How to initialise an empty ComponentRef?

使用 Angular 11 和 Typescript 严格模式我有:

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');

  }

}

我收到错误:

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

解决这个问题的最佳方法是什么?

是否可以初始化一个空的 ComponentRef?

这可能是因为严格模式。

你能试试这个吗?

component!: ComponentRef<any>;

注意“!”在组件之后。