您可以将 #local reference" 添加到包含您的元素的 ng-container 或 div,然后在您的代码中,用@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.