Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What kinds of changes do ViewChildren and ContentChildren QueryLists listen for?

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.

like image 924
NetherGranite Avatar asked Jul 03 '17 20:07

NetherGranite


People also ask

What happens when a child element is added to the querylist?

Any time a child element is added, removed, or moved, the query list will be updated, and the changes observable of the query list will emit a new value. The QueryList is initialized only before the ngAfterViewInit lifecycle hook, therefore, is available only from this point. ViewChildren don’t include elements that exist within the ng-content tag.

Why use @viewchildren and contentchildren instead of getElementById?

Using @ViewChildren and ContentChildren will also return a QueryList which provides an observable that you can watch for changes, so it works much more nicely in the Angular environment than using getElementById does (as tempting as that may be).

What is the syntax of the viewchild query in JavaScript?

The ViewChild query returns the first matching element from the DOM and updates the component variable on which we apply it. The Syntax of the viewChild is as shown below. We apply the viewChild decorator on a Component Property. It takes two arguments. A selector and opts.

What is the use of viewchild and viewchildren decorators?

The ViewChild or ViewChildren decorators are used to Query and get the reference of the DOM element in the Component. ViewChild returns the first matching element and ViewChildren returns all the matching elements as a QueryList of items.


1 Answers

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.

like image 172
Reactgular Avatar answered Oct 06 '22 18:10

Reactgular