[英]How I can access DOM element by selector
在 Angular2 中,有沒有辦法通過它的選擇器而不是在模板中而是在整個 DOM 中獲取元素?
不建議在 angular2 中直接訪問 DOM,因為您繞過了 Angular2 渲染器
您可以使用其他 angular 2 功能來執行此操作,例如:添加對此元素的引用。
看看這個問題,它可以幫助你: How to get dom element in angular 2
當然, window.document.querySelector
或window.document.querySelectorAll
。
我將把它作為另一個答案發布,而不是編輯舊的,因為恕我直言,這兩種方法都很有用。 但這絕對是一個更“Angularish”的。
有兩種 Angularish-2 方法可以獲取對模板 DOM 元素的引用; ElementRef 和 ViewChild。 可能還有更多,但這是隨處可見的兩個。
ElementRef 可能最好避免。 顯然,它讓您面臨潛在的 XSS 攻擊。 文檔周圍有各種紅色的“當心”。
所以我選擇了一些非常有效的東西,那就是 ViewChild。
我的模板:
<input #myinput type="text" />
請注意看起來很奇怪的#myInput。 它用作 ID,但不是普通的 DOM id=''。 我認為這可以讓您解決唯一 ID 問題,以及使用空 CSS 類代替 ID 標記元素的丑陋技巧。
在您的代碼中:注意我使用沒有注釋的 ES6。 但要獲得相同的效果,您可以使用 @ViewChild 注釋。 它在 TS 中得到了很好的記錄(根本不在 ES6 中,我花了很長時間才把它拼湊起來)。
僅供參考,我必須想出一種干凈的方法來做到這一點,因為我想實現一個 RxJS 流來執行一些去抖動等操作。
import { Component, ngOnInit, ViewChild } from '@angular/core';
class HomeComponent {
constructor( ) {}
ngOnInit ( ) {
// .nativeElement console.log's out to what you'd expect.
var inputBox = this.myInputRef.nativeElement;
// left this in to demonstrate it works as plain ol' DOM elem,
// if it didn't, this wouldn't work.
var source = Rx.Observable.fromEvent(inputBox, 'click');
...
}
}
HomeComponent.annotations = [
new Component ( {
templateUrl: './views/home/home.component.html',
queries: { 'myInputRef': new ViewChild ( 'myinput' ) }
} )
];
export { HomeComponent }
奇跡般有效。 是時候我們在 Angular 中遇到了這樣的事情。 JQLite 真的從來沒有剪過它。
今天有一種使用 Document 查詢元素的“Angular”方式:
import { Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
class DOMService {
constructor(@Inject(DOCUMENT) private document) {}
getElementsByClass(clazz: string): HTMLCollection[] {
return this.document.getElementsByClassName(clazz);
}
}
特別是對於服務器端渲染功能,例如不建議直接訪問window
( window && window.document..
)。 如果您還操作元素,您應該考慮使用 Angulars Renderer2
如果您只需要訪問當前組件中的 Element,您可以使用@ViewChild
或ElementRef
功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.