将SVG动态添加到SVG根元素中

问题描述 投票:1回答:1

我想将rect等SVG元素动态添加到SVG根元素。这一点现在可以正常工作,但是不会重新渲染SVG,因此不会显示新的SVG元素。

我正在研究这个问题,并且在Angular github页面上发现了类似的问题:

我尝试了这些解决方案,但是我无法使新添加的SVG元素显示在浏览器中。

这是我到Stackblitz的链接:https://stackblitz.com/edit/angular-ivy-dj7wto?file=src%2Fapp%2Fparent%2Fparent.component.ts

有人可以帮助解决这个问题吗?

javascript angular typescript svg
1个回答
0
投票

[当您使用推荐的OnPush策略时,在这种情况下,您必须自行触发更改检测,否则视图将无法反映更改:

// Inject the change detector service
constructor(..., private _cd: ChangeDetectorRef) {} 

createComponent() {
  let componentFactory = this.CFR.resolveComponentFactory(ChildComponent);
  let childComponentRef = this.VCR.createComponent(componentFactory);

  let childComponent = childComponentRef.instance;
  childComponent.unique_key = ++this.child_unique_key;
  childComponent.parentRef = this;

  // add reference for newly created component
  this.componentsReferences.push(childComponentRef);

  this._cd.markForCheck(); // <= fires the change detection
}
© www.soinside.com 2019 - 2024. All rights reserved.