Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 334
I.Bond Avatar asked Oct 18 '19 14:10

I.Bond


1 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);
like image 125
Ludevik Avatar answered Oct 04 '22 15:10

Ludevik