首页 > 解决方案 > 操作未渲染的 DOM 元素以在 Angular 中导出

问题描述

我创建了一个 Angular 服务来为用户导出一个 SVGElement。简而言之,它构建了一个 SVG 并将符号附加到<defs>. 然后,服务使用 Promise 将此 SVG 返回给组件,组件将其复制到剪贴板或将其导出为文件。

我的问题是导出的 SVG 元素在组件尝试导出它时为空。setTimeout()如果我在服务中插入 a resolve(svgElement),它就可以工作。

如何以更同步的方式操作这些动态生成的 DOM 元素?SVG 永远不会为用户呈现。

这是一些简化的代码来尝试说明功能。

\\ service.ts
public exportToSVG(ids: string[]): Promise<SVGElement> {
   return new Promise((resolve, reject) => {
      const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
      const defs = document.createElement('defs');

      ids.forEach(async id => {
         // use another method to get the symbol associated with the id
         const symbol = await this._getSymbolByString(id);
         defs.appendChild(symbol);
      });

      svg.appendChild(defs);
      resolve(svg);
   });
}

\\ component.ts
public copyToClipboard(ids: string[]) {
   this.myService.exportToSVG(ids).then(svg => {
      // this only copies `<svg><defs></defs></svg>`, unless a setTimeout is used
      this.clipboardService.copyFromContent(svg.outerHTML);
   });
}

标签: javascriptangularsvgdom

解决方案


我通过链接 Promises 解决了这个问题,而不是使用异步...等待。


推荐阅读