angular - 如何初始化一个空的 ComponentRef?
问题描述
使用 Angular 11 和 Typescript Strict 模式我有:
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>;
注意“!” 在组件之后。
推荐阅读
- javascript - 根据下拉选择在 PUG 模板中加载 HTML 表
- sql - 无论是否存在子记录都返回父记录的 SQL 查询
- mongodb - MongoDB:用点和作为对象查询嵌套字段 - 区别?
- python - Spotipy - 输入任何类型的用户名并询问登录信息
- javascript - dotenv 不适用于无服务器/webpack
- c# - 如何使用 model.id 动态生成 HTML 属性值?
- c# - 如何在选择子句中使用表达式
- spring - 使用 mongo 数据分页提高性能
- jasmine - Karma/Jasmine/PhantomJS “TypeError:_this.handler.handle 不是函数”
- image - 如何在左右隔室(半)中划分大脑分段切片?