任何人都可以帮助如何在Angular 2中找到具有特定类名的"All"元素吗?我认为这将是微不足道的,但它给了我更多准备好的问题.
<span class="classImLookingFor">foo</span>
<span class="classImLookingFor">Voo</span>
<span class="classImLookingFor">Moo</span>
Run Code Online (Sandbox Code Playgroud)
我认为通过执行下面的操作会返回类"classImLookingFor"的所有元素,但它只返回第一个实例.
constructor(private renderer: Renderer){}
ngAfterViewInit(){
const el = this.renderer.selectRootElement('.classImLookingFor');
this.renderer.setElementAttribute(el, 'tabindex', 0);
}
Run Code Online (Sandbox Code Playgroud)
之后,我的标记看起来像这样.
<span class="classImLookingFor" tabindex="0">foo</span>
<span class="classImLookingFor">Voo</span>
<span class="classImLookingFor">Moo</span>
Run Code Online (Sandbox Code Playgroud)
看起来我应该能够创建一个Renderer数组,但这似乎也不起作用.我需要用该类名操作每个元素.提前致谢
Par*_*osh 28
这不会返回DOM中的所有元素吗?有没有办法如何只返回Angular组件生成的元素?
你需要...
注入ElementRef的constructor
constructor(private renderer: Renderer, private elem: ElementRef){}
Run Code Online (Sandbox Code Playgroud)使用querySelectorAllapi 查找要搜索的元素.
ngAfterViewInit(){
// you'll get your through 'elements' below code
let elements = this.elem.nativeElement.querySelectorAll('.classImLookingFor');
}
Run Code Online (Sandbox Code Playgroud)@Aravind提供的答案不是最佳的性能,因为它将搜索整个DOM.
该解决方案将仅搜索当前组件内的DOM.
Nex*_*euz 10
Angular 10+ 文档与 SSR 的兼容性,导入:
import { DOCUMENT } from '@angular/common'
Run Code Online (Sandbox Code Playgroud)
然后注入:
constructor(@Inject(DOCUMENT) private _document: HTMLDocument) {
}
Run Code Online (Sandbox Code Playgroud)
并在您的组件/指令中使用,如下所示:
doSomething(): void {
this._document.querySelectorAll('.classImLookingFor')
}
Run Code Online (Sandbox Code Playgroud)
回答评论时对OP起作用。
您应该使用
document.querySelectorAll('.classImLookingFor')
Run Code Online (Sandbox Code Playgroud)
对于您的用例来说,这可能有点过于简单化,但是有什么原因您不能像这样使用本机 DOM 函数吗?
var domRepresentation = document.getElementsByClassName('classImLookingFor');
var angularElement = angular.element(domRepresentation);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
31406 次 |
| 最近记录: |