Selecting viewchild with 1 hash selection in angular 2

4k views Asked by At

Is there a trick to select multiple tag within same level with same tag?

<div #el></div>
<div #el></div>
<div #el></div>

It's always given "Reference "#el" is defined several times" error message.

Thanks in advance

3

There are 3 answers

6
Dhaval kansagara On

Include ViewChildren.

import {Component, ViewChildren} from 'angular2/core'

Now you can use the following code.

@ViewChildren('el') components:QueryList<ElementRef>;
0
user5436320 On

Oh nevermind.. I got another way, but not so neat

<div #el>
  <div el></div>
  <div el></div>
  <div el></div>
</div>

Then for select all use querySelectorAll

@ViewChild('el') element: ElementRef;
this.element.nativeElement.querySelectorAll('[el]')

Thanks All

2
Dipak Delvadiya On

Below approach is working fine for me for multiple elements with appropriate selector.

I have an requirement to load the popup modal dynamically from code base and also perform some actions like Minimize, Maximize, Close and Resize. At that time I have to pick the any one opened modal to perform some operation and I came up with this solution.

Below is my HTML, In which I used #dynamicPopupContentPlaceHolder as selector for div tag.

enter image description here

Firstly, Need to add the QueryList in component from angular/core library as shown below.

enter image description here

Finally, In the component file I used the QueryList (Contains the array of children) to get all the children using below way.

enter image description here

At end I used the widgetSelector variable to get the last child from array using below way.

let _targetSelector = this.widgetTargets.last;