我试图动态创建新元素并将其添加到DOM,作为子实体。这是到目前为止我发现的唯一方法,但是我是否在不使用HTMLElements的情况下是否有更好的方法感到有些怀疑。
// 1. Create a component reference from the component
this.componentRef = this.componentFactoryResolver
.resolveComponentFactory(ModalComponent)
.create(this.injector);
// 2. Set Inputs
this.componentRef.instance.inputText = text;
// 3. Attach component to the appRef so that it's inside the ng component tree
this.appRef.attachView(this.componentRef.hostView);
// 4. Get DOM element from component
const domElem = (this.componentRef.hostView as EmbeddedViewRef<any>)
.rootNodes[0] as HTMLElement;
// 5. Append DOM element to the body
this.renderer.appendChild(document.body, domElem);
对于这种方法,我们需要以下依赖项:
constructor(private rendererFactory: RendererFactory2,
private componentFactoryResolver: ComponentFactoryResolver,
private appRef: ApplicationRef,
private injector: Injector) {
this.renderer = rendererFactory.createRenderer(null, null);
}
是否有更好的方法?也许和ViewChild在一起?
所以我可以简单地做到这一点(假设bodyElement是通过ViewChild初始化的ViewContainerRef):
const factory = this.resolver.resolveComponentFactory(MessageComponent);
this.componentRef = this.bodyElement.createComponent(factory);