我已經向組件添加了一個外部腳本,如下所示:
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 的例子,但這假設您可以控制元素并且它不是動態創建的。
如何動態定位元素,類似于使用事件委托但有角度的?
uj5u.com熱心網友回復:
您可以將#local 參考添加到包含您的元素的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文章這里:
為什么不是 ElementRef?
我們可以使用 ElelemtRef 的 nativeElement 屬性來操作 DOM。 nativeElement 屬性包含對底層 DOM 物件的參考。這讓我們可以直接訪問 DOM,繞過 Angular。
使用它沒有任何問題,但不建議使用,原因如下:
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.
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/404549.html
標籤:
