【问题标题】:Remove dynamically created element by id in angular component通过角度组件中的 id 删除动态创建的元素
【发布时间】:2022-01-07 09:35:49
【问题描述】:

我已经向组件添加了一个外部脚本,如下所示:

ngAfterViewInit() {
  let s = document.createElement("script");
  s.id = "hs-script-loader";
  s.async = true;
  s.src = "//some-url.com/12345.js";
  this.element.nativeElement.appendChild(s);
}

脚本实际上加载了一个实时聊天小部件,该小部件是在加载脚本时在 DOM 中动态创建的。

我想在组件被销毁时从 DOM 中删除该元素,但我不确定如何创建对动态创建的元素的引用。

我见过使用 elementRef 的示例,但这假设您可以控制元素并且它不是动态创建的。

我如何动态地定位元素,类似于使用事件委托但在角度?

【问题讨论】:

    标签: javascript angular typescript dom


    【解决方案1】:

    您可以将 #local reference" 添加到包含您的元素的 ng-containerdiv,然后在您的代码中,用@ViewChild链接引用,最后用:

    @ViewChild('yourLocalReferenceHTMLname') private yourLocalReferenceHTMLname: ElementRef;
    
    this.yourLocalReferenceHTMLname.nativeElement.remove();
    

    无论如何,尽量不要使用 elementRef [来自 Angular 文档]:

    当需要直接访问 DOM 时,使用 elementRef API 作为最后的手段。改用 Angular 提供的模板和数据绑定。 或者,您可以使用 Renderer2,它提供的 API 即使在不支持直接访问本机元素的情况下也可以安全使用。

    依赖直接 DOM 访问会在您的应用程序和渲染层之间创建紧密耦合,这将导致无法将两者分开并将您的应用程序部署到 Web Worker 中。

    从字面上看,来自这篇render2文章HERE

    为什么不用 ElementRef?

    我们可以使用 ElelemtRef 的 nativeElement 属性来操作 DOM。nativeElement 属性包含对底层 DOM 对象的引用。这让我们可以绕过 Angular 直接访问 DOM。

    使用它没有错,但不建议使用,原因如下:

    Angular keeps the Component & the view in Sync using Templates, data binding & change detection, etc. All of them are bypassed when we update the DOM Directly.
    
    DOM Manipulation works only in Browser. You will not able to use the App in other platforms like in a web worker, in Server (Server-side rendering), or in a Desktop, or in the mobile app, etc where there is no browser.
    
    The DOM APIs do not sanitize the data. Hence it is possible to inject a script, thereby, opening our app an easy target for the XSS injection attack.
    

    【讨论】:

    • 您好胡安,感谢您的回复。不幸的是,我认为我无法控制外部脚本将元素放置在何处,因为它在结束正文标记之前注入它,这超出了我的控制范围。感谢您提供了很好的信息来解释为什么直接 DOM 操作并不理想。听起来并没有一个真正理想的解决方案来处理这个特定的问题,所以我现在可能会离开这个。感谢您的指导。
    猜你喜欢
    • 2016-09-26
    • 1970-01-01
    • 2014-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多