ps0604
ps0604

Reputation: 1071

Clearing ViewChildren subscriptions on destroy

I have the following declaration in an Angular 8 component:

@ViewChildren(SelectComponent) selects: QueryList<SelectComponent>;

where SelectComponent is declared N times in an *ngFor.

To loop through the selects array when there are any edits, I subscribe to the changes:

this.selects.changes.subscribe(list => {
            list.forEach(item => {
                 alert('in forEach');
                // do something
            });
        });

The loop works fine, but the problem is that when I close and reopen the main component, the previous selects apparenty are not cleared, because the alert shows up several times.

How to clear/unsubscribe from these subscribes when the component is closed?

Upvotes: 2

Views: 1367

Answers (3)

Morphyish
Morphyish

Reputation: 4072

From memory, you store the subscription in a variable inside your component

this.mySubscription = this.selects.changes.subscribe(list => {
            list.forEach(item => {
                 alert('in forEach');
                // do something
            });
        });

and then you unsubscribe inside the ngOnDestroy part of the component lifecycle

public ngOnDestroy(): void {
    this.mySubscription.unsubscribe();
}

Upvotes: 1

Rydyell
Rydyell

Reputation: 31

Try adding the NgOnDestroy method to your component - https://angular.io/api/core/OnDestroy Adding that should clear any previous subscriptions on reloads.

Upvotes: 0

bryan60
bryan60

Reputation: 29335

the same way you clear any other subscription, by unsubscribing in OnDestroy hook:

private sub: Subscription;

this.sub = this.selects.changes.subscribe(list => {
        list.forEach(item => {
             alert('in forEach');
            // do something
        });
    });

 ngOnDestroy() { this.sub.unsubscribe(); }

Upvotes: 3

Related Questions