【问题标题】:How to clear element from all children in Angular (5+) Renderer2?如何从Angular(5+)Renderer2中的所有子项中清除元素?
【发布时间】:2018-05-10 16:16:34
【问题描述】:

建议使用 Angular Renderer2 以编程方式操作 DOM。

在我的指令中,我使用了一些 el.nativeElement.innerText,转换此文本并希望将其添加到我的元素中:

const text = renderer.createText(`${el.innerText}%`); renderer.appendChild(el, text);

问题在于el - 它已经有文本,所以它会在其后附加转换后的文本。

我检查了 Renderer2 文档,看来我可以使用 removeChild() 而不传递对子项的引用,所以我不能先使用 Renderer2 清除组件?

在这种情况下,实现它的唯一方法是在渲染器方法之前使用innerText = '',这使得它毫无意义。

【问题讨论】:

    标签: angular angular5


    【解决方案1】:

    这是正确的代码:

    
        const childElements = this.el.nativeElement.childNodes;
        for (let child of childElements) {
          this.renderer.removeChild(this.el.nativeElement, child);
        }
    
    

    【讨论】:

    • 这是正确的,.children 是有问题的,因为 HTMLCollection (this.el.nativeElement.children) 与 NodeListOf (this.el.nativeElement.childNodes) 的支持方法的限制,大多数主要是 forEach 方法。
    【解决方案2】:

    这是使用 while 循环的另一个选项。只要第一个位置存在子元素,就会从集合的末尾移除子元素。

    const myEl = this.el.nativeElement;
    
    while(myEl.firstChild) {
      this.renderer.removeChild(myEl, myEl.lastChild);
    }
    

    【讨论】:

      【解决方案3】:

      可能是这样的:

      const childElements = this.el.nativeElement.children;
      for (let child of childElements) {
        this.renderer.removeChild(this.el.nativeElement, child);
      }
      

      【讨论】:

        【解决方案4】:

        这对我有用:

        element.nativeElement.childNodes.forEach(node => {
          this.renderer.removeChild(element.nativeElement, node)
        })
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-05-04
          • 2013-10-02
          • 2015-09-16
          • 2015-11-30
          • 1970-01-01
          • 2012-09-01
          • 1970-01-01
          • 2018-04-05
          相关资源
          最近更新 更多