Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do you have to unsubscribe from a QueryList in a component?

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.

like image 1000
Reactgular Avatar asked Jul 18 '18 00:07

Reactgular


People also ask

What is a 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.

How do you use ContentChildren?

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.

How do you use ViewChildren?

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.


1 Answers

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.

like image 105
kashpatel Avatar answered Oct 17 '22 05:10

kashpatel