Is any ways to get ElementRef and Component ref in ViewChildren?

Viewed 6381

I want to get a list of native elements and related components to them from view.

I'll try to do something like that, but it's not work:

@ViewChildren('element', { read: [ElementRef, MyComponent] }) private elements: QueryList<any>; // <-- not work

or

@ViewChildren('element', { read: MyComponent }) private elements: QueryList<MyComponent>;
...
this.elements.first.nativeElement // <-- undefined

This work, but it doesn't look right:

@ViewChildren('element', { read: ElementRef }) private elements: QueryList<ElementRef>;
@ViewChildren('element', { read: MyComponent}) private components: QueryList<MyComponent>;

my template short example:

<virtual-scroller #scroll>
  <my-component #element *ngFor="let c of components"></my-component>
</virtual-scroller>
3 Answers

One way to do this is to inject:

@ViewChildren('element', { read: MyComponent}) private components: QueryList<MyComponent>;

in parent component and expose elementRef from child:

class MyComponent {
    constructor(public elementRef: ElementRef) {}
}

and then just access elementRef directly:

this.components.forEach(component => component.elementRef);

One way to solve it is to inject in each component the ElementRef as a public property and then, by iterating over the components(resulted from ViewChildren), you can access everything you want.

my-component.component.ts

@Component({ /* ... */ })
export class MyComponent {
 /* ... */

 constructor (public elementRef: ElementRef) { }

 /* ... */
}

parent.component.html

<virtual-scroller #scroll>
  <my-component #element *ngFor="let c of components"></my-component>
</virtual-scroller>

parent.component.ts

@ViewChildren('element', { read: MyComponent }) private components: QueryList<MyComponent>

/* ... */

ngAfterViewChecked () {
 this.components.forEach(c => console.log(c.elementRef))
}
Related