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
.
As a general rule, it's good to unsubscribe from things that you have subscribed to when your component is destroyed. In Angular, you can do this in your ngOnDestroy method.
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.