Kristievnee
Kristievnee

Reputation: 43

Angular2 add nativeElement to component's prototype

This might be totally stupid question (Hey! thats great for SO ...). Here is my problem: I have multiple *ngFor in my main module template which actually repeat child component and I am adding classes and inline styles to it directly via ViewChildren decorator in parent component (vith QueryList and ElementRef). The parent template looks pretty basic, like this:

<div #child *ngFor="let child of children">
  <app-child-component></app-child-component>
</div>

the parrent component looks something like this:

@ViewChildren('child') children_elements: QueryList<ElementRef>;
... do whatever I do with children ...

I know that I can bind classes and style within the child component or to use ngStyle / ngClass. But these are no good to me since I have specific use case where I need to target template children based on their index in template and I need to inject them into the template dynamically from an array. Well, all is good with my solution, but I wonder if I can get rid of that wrapping div element so I would repeat only the child component like this:

  <app-child-component #child *ngFor="let child of children"></app-child-component>

The problem is, I guess, that the Angular's QueryList is unchangeable, so I cannot add or remove class or style to its items. The same goes with elementRef and Renderer or with good old classy querySelectorALl() called on host element (i.e. this.elementRef.childNodes or document.querySelectorALl('child') ... there simply are no 'nativeElement' on its children nodes and there is no 'style' or 'classList' or anything like that on it neither.

I doubt that I am asking the right question but on my mind it sounds like this: "Can I somehow enhance my child component so when it is accessed from its parent via ViewChildren it has something like .elementRef.nativeElement?" Or "Is there other way to access template view to be able to manipulate with repeated injected components?" (I tried to read docs on ViewRef, EmbeddedView and others, but it makes me nuts ...).

If you think this is crap and I should not even asked, please, just downvote this, I would probably do that myself ...

Thanks!

Upvotes: 0

Views: 1358

Answers (1)

yurzui
yurzui

Reputation: 214047

You can specify read property like

@ViewChildren('child', { read: ElementRef }) children_elements: QueryList<ElementRef>;

See also

Upvotes: 2

Related Questions