9

Let's say you had the following code:

<code>@ViewChildren('item') items: QueryList<any>;</code>

And somewhere else the code:

<code>this.items.changes.subscribe(() => {})</code>

What are the changes that would cause () => {} to be called? What about @ContentChildren()? I couldn't find any documentation on this.

Additionally, is there a way to get more information about the change that happened? (e.g. the type of change, the element with which the change occurred, etc.)

EDIT: The answer to the "Additionally" portion above can be found in the comments section of the answer that is marked correct.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
NetherGranite
  • 1,940
  • 1
  • 14
  • 42

1 Answers1

9

Both @ViewChildren and @ContentChildren are used to get a list of Angular components.

So if you have a component ItemComponent the binding would be like this.

@ViewChildren(ItemComponent) items: QueryList<ItemComponent>;

QueryList will be a list of objects that are of ItemComponent type.

The events in the query list emit when the number of items in the list has changed. Either a component was added or destroyed. This can often often happen when *ngFor is used or other template modifiers.

NetherGranite
  • 1,940
  • 1
  • 14
  • 42
Reactgular
  • 52,335
  • 19
  • 158
  • 208
  • 1
    Can I have template reference variable #test? I don't understand why @ViewChildren('test') example will always yield an empty list. – yurzui Jul 03 '17 at 20:45
  • 1
    @yurzui sorry. You are correct. A string selects a template `#` name and the type will be `ElementRef`. I thought it was for tokens. – Reactgular Jul 03 '17 at 20:56
  • Ah, thank you for your answer. Just one more thing: is there a way to get information about the specific change that occurred? – NetherGranite Jul 03 '17 at 21:21
  • 1
    @NetherGranite No, the way the logic works inside Angular is to emit a change event every time a template operation changes the DOM structure. I don't even think it bothers to figure out what has changed. Only that it did change. If I needed to track this. I would iterate the items in the query list and tag them with extra data. Any missing that tag would be new items and if the tag is a position then any skips in a number would indicate a deleted item. – Reactgular Jul 03 '17 at 22:13
  • @ThinkingMedia Ah, okay. Thank you! – NetherGranite Jul 03 '17 at 23:07