Angular2检索具有类名称的所有元素 [英] Angular2 retrieve all elements with class name

查看:84
本文介绍了Angular2检索具有类名称的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以在Angular 2中帮助找到具有特定类名称的所有"元素吗?我以为那是微不足道的,但这给了我很多准备的问题.

Can anyone help with how to find 'All' Elements with a particular class name in Angular 2? I thought it would be trivial but it's giving me more problems that was prepared for.

<span class="classImLookingFor">foo</span>
<span class="classImLookingFor">Voo</span>
<span class="classImLookingFor">Moo</span>

我认为通过执行下面的操作,将返回类"classImLookingFor"的所有元素,但它仅返回第一个实例.

I thought by doing what I have below would return all the elements with class "classImLookingFor" but it only returns the first instance.

constructor(private renderer: Renderer){}
ngAfterViewInit(){
 const el = this.renderer.selectRootElement('.classImLookingFor');
 this.renderer.setElementAttribute(el, 'tabindex', 0);
}

然后,我的标记如下所示.

Afterwards, my markup looks like this.

<span class="classImLookingFor" tabindex="0">foo</span>
<span class="classImLookingFor">Voo</span>
<span class="classImLookingFor">Moo</span>

似乎我应该能够创建一个Renderer数组,但这似乎也不起作用.我需要使用该类名称来操纵每个元素.在此先感谢

It seems like I should be able to create a Renderer array, but that doesn't seem to work either. I need to manipulate each element with that class name. Thanks in Advance

推荐答案

这不返回DOM中的所有元素吗?有没有办法只返回我在"Angular"组件中生成的元素?

Doesn't this return all the elements in the DOM? Is there a way how to return only elements generated by the Angular component I'm "in"?

您需要...

  1. constructor

constructor(private renderer: Renderer, private elem: ElementRef){}

  • 使用querySelectorAll api查找要搜索的元素.

  • Find the elements you are searching using querySelectorAll api.

    ngAfterViewInit(){
        // you'll get your through 'elements' below code
        let elements = this.elem.nativeElement.querySelectorAll('.classImLookingFor');
    }
    

  • @Aravind 提供的答案并不是最佳的性能,因为它将搜索整个DOM.

    The answer @Aravind has provided is not the best for the performance as it will search the whole DOM.

    此解决方案将仅在当前组件内搜索DOM.

    This solution will just search the DOM inside the current component.

    这篇关于Angular2检索具有类名称的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆