[英]Get DOM element which is a component in Angular
我已經在這里讀了一些答案,比如這個 ,但我的問題略有不同。 我想將組件作為DOM元素,以便我可以在其上添加/刪除一些CSS類。
我的HTML模板包含組件:
<sidenav-menu #sidenav class="app__sidenav"></sidenav-menu>
我的類包含對它的引用:
@ViewChild('sidenav') sidenav: ElementRef;
但是當我在我的一個函數中記錄this.sidenav
時,我發現它是一個Sidenav組件類的表示,而不是它的DOM表示。 為什么會這樣?
您可以使用read
參數指定所需內容:
@ViewChild('sidenav', {read: ElementRef}) sidenav: ElementRef;
這樣你就得到了ElementRef
並且可以使用像this.sidenav.nativeElement
提到的this.sidenav.nativeElement
或(對於其他用例)
@ViewChild('sidenav', {read: ViewContainerRef}) sidenav: ElementRef;
我的回答對你喜歡的問題也提到了這一點read
參數https://stackoverflow.com/a/35209681/217408
編輯
為了實現這一點,您需要實現@GünterZöchbauer建議,使用ViewChild
read
組件。
原始答案
您需要使用ElementRef
對象的nativeElement
屬性。 你會在那里找到你的DOM表示。 它也暴露了DOM元素,並允許您在其上調用傳統方法,就好像它是vanilla javascript或jQuery中的DOM元素一樣。
console.log(this.sidenav.nativeElement);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.