2017-10-10 102 views
1

我是Angular2的新手,我不得不在Angular2中获得下一个元素值/文本,但我无法做到这一点。在Jquery中非常容易,但我没有找到任何方法在Angular2中实现相同。请帮忙。如何获得Angular2中的下一个元素/兄弟姐妹

这里是我的代码:

<div id="div1">Here is Div-1 content</div> 
<div id="div2">Here is Div-2 content</div> 

在jQuery中这是很容易做到的,如:

$('#div1').next().text(); 

如何同样可以在角2

+0

可能的重复[DOM操作属于Angular 2?](https://stackoverflow.com/questions/37376442/where-does-dom-manipulation-belong-in-angular-2) – asmmahmud

+0

否, 不是这样。我的问题是不同的。 – Ankit

+0

类似于https://stackoverflow.com/questions/32693061/angular-2-typescript-get-hold-of-an-element-in-the-template?noredirect=1&lq=1 – asmmahmud

回答

0

可以做,你可以使用元素引用和使用与jQuery中相同的方式。

注入元素引用您的组件

constructor(private elementRef: ElementRef) { 

    } 

然后使用查询选择

this.elementRef.nativeElement.querySelector('.div1').style.display = 'none'; 
+0

是的,这可以给我什么我想要,但我在任何其他方式流浪。有没有其他方法? – Ankit

+0

@ViewChild也在那里,但不知道,没有尝试过。你也可以看看。您也可以将一些组件变量绑定到标签。我认为还有其他方法。 –

1

我想你在找什么是没有棱角具体的事情,但至少在JavaScript,你可以做这个:document.getElementById('div1').nextSibling您可以在其中找到所述元素的属性。你可以增加索引来寻找下一个兄弟,或者检查孩子,等等等等。

You can read about implementation here on MDN.

希望这有助于。 :)