What is the correct way to destroy an element created with Renderer2?

In our code base, we have a virtual replay directive that uses Renderer2 to create a div as follows:

this.renderer2.createElement('div');

In the ngOnDestroy method, we destroy it as follows:

this.renderer.destroyNode(this.offsetBeforeEl);

This worked well and we had no problems until we built the application in prod mode and we started getting the following error:

main.js?d73b003:formatted:87193 Uncaught (in promise) TypeError: this.renderer.destroyNode is not a function

I added a breakpoint to this line and found that actually destroyNode is not a method on Renderer2. I went to the source code for angular and found a comment above the method in the abstract defintion class:

/**
   * This property is allowed to be null / undefined,
   * in which case the view engine won't call it.
   * This is used as a performance optimization for production mode.
   */
  destroyNode: ((node: any) => void)|null; 

So, I checked the code for the view and saw this:

if (view.renderer.destroyNode) {
  destroyViewNodes(view);
}
if (isComponentView(view)) {
  view.renderer.destroy();
}

If I cannot rely on this existing method, what is the correct way to destroy a node that was dynamically created using Renderer2?

+4
1

renderer.removeChild.

prod

destroyNode DebugRenderer2, .

node , angular, , execRenderNodeAction:

function execRenderNodeAction(
    view: ViewData, renderNode: any, action: RenderNodeAction, parentNode: any, nextSibling: any,
    target?: any[]) {
  const renderer = view.renderer;
  switch (action) {
    case RenderNodeAction.RemoveChild:
      renderer.removeChild(parentNode, renderNode);
      break;

, removeChild :

    const parent = this.renderer.createElement('div');
    const child = this.renderer.createElement('span');
    this.renderer.appendChild(parent, child);

    // using remove child
    this.renderer.removeChild(parent, child);
+2

Source: https://habr.com/ru/post/1678904/


All Articles