“ComponentFactoryResolver 已弃用”新实现缺少属性?

Bál*_*thy 5 angular

从 Angular 13ComponentFactoryResolver开始已弃用。我找不到可以正确替换它的解决方案,因为rootSelectorOrNode新解决方案中缺少旧参数。

我想RectComponent动态创建并将其绑定到动态创建的 SVG 矩形元素。

这是我的旧解决方案:

public createRectComponent(representation:Shape<SVGRectElement>, viewContainerRef?:ViewContainerRef|null, vcrIndex?:number):ComponentRef<RectComponent>{
    const rectNode:SVGRectElement = representation.element || this.renderer.createElement('rect', 'http://www.w3.org/2000/svg') as SVGRectElement;
    representation.element = rectNode;
    const rectComponentFactory = this.componentFactoryResolver.resolveComponentFactory(RectComponent);
    viewContainerRef = viewContainerRef || this.artAccessVcr;
    const rectComponentRef = rectComponentFactory.create(viewContainerRef!.injector, [], rectNode);
    viewContainerRef!.insert(rectComponentRef.hostView, vcrIndex);
    return rectComponentRef;
}
Run Code Online (Sandbox Code Playgroud)

新的方式应该是这样的:

    ...
    const rectComponentRef = viewContainerRef!.createComponent(RectComponent, {
      injector: viewContainerRef!.injector,
      projectableNodes: [],
      //rootSelectorOrNode: rectNode //This attribute is missing completly
    });
    ...
Run Code Online (Sandbox Code Playgroud)

我在文档中找不到任何对此有帮助的信息,但我认为这不应该是一个特定的问题,因为很多第三方库提供了一个预定义的 html 节点,您可以使用它来绑定角度逻辑。这里的情况并非如此,但我仍然更愿意自己定义 svg 节点元素。

感谢您的时间和答复!

yur*_*zui 1

您应该使用新的createComponent函数,它允许您hostElement作为options

import { EnvironmentInjector, ... } from '@angular/core';

...

constructor(private envInjector: EnvironmentInjector, ...) {}

...
const rectComponentRef = createComponent(RectComponent, { 
   environmentInjector: this.envInjector,
   hostElement: rectNode 
});
Run Code Online (Sandbox Code Playgroud)

Stackblitz 已弃用带有 ComponentFactoryResolver 的版本

带 createComponent 的新版本