When using the @ContentChildren
or @ViewChildren
decorators to listen for changes to DOM elements. Do I have to unsubscribe from the QueryList
?
For example:
@Component({...})
export class ParentComponent implements AfterContentInit {
@ContentChildren(ChildComponent)
public children: QueryList<ChildComponent>;
public ngAfterContentInit(): void {
this.children.changes.subscribe(() => ....);
}
}
Would the above be a problem?
Updated:
The reason I'm asking is that we don't have to unsubscribe to @Output
decorators. These are automatically unsubscribed by the component when it is destroyed.
I can not find any documentation which says this is the same for the QueryList
.
The return type of ViewChildren is QueryList . QueryList is just a fancy name for an object that stores a list of items. What is special about this object is when the state of the application changes Angular will automatically update the object items for you.
To use ContentChild , we need to import it first from the @angular/core . import { Component, ContentChild, ContentChildren, ElementRef, Renderer2, ViewChild } from '@angular/core'; Then use it to query the header from the projected content.
The Viewchild can also be used to query HTML elements. First, assign a Template variable ( #para in the example below) to the HTML element. You can then use the ViewChild to query the element. ViewChild returns a ElementRef , which is nothing but a wrapper around the native HTML element.
You don't have to unsubscribe from QueryList. It does it for you.
See here: https://github.com/angular/angular/blob/7d137d7f8872a6fba72668e32f9baf2c5dcfc48b/packages/core/src/linker/query_list.ts#L115
As a general rule, I unsubscribe when Observable stays alive after Component destroyal. Works in most scenarios.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With