Using single ngOnDestroy in parent component

Discussão em 'Angular' iniciado por Francesco, Agosto 28, 2025.

  1. Francesco

    Francesco Guest

    In our application we have some components that inherit from a BaseComponent.

    The base component implements OnDestroy interface and emits with a Subject to notify the children to unsubscribe from eventual open streams.

    Is this an acceptable approach or rather every single component should have its own ngOnDestroy implementation? From this article I read that Lifecycle hooks are not inherited.

    BaseComponent

    export abstract class ComponentBase implements OnDestroy {
    protected destroy$ = new Subject<boolean>();

    ngOnDestroy() {
    this.destroy$.next(true);
    }
    }


    ChildComponent

    export class ChildComponent extends ComponentBase implements OnInit {

    ngOnInit() {
    this.service
    .getById(userId)
    .pipe(takeUntil(this.destroy$)) // this is emitted by the parent
    .subscribe(user => { ...}
    }
    }

    Continue reading...

Compartilhe esta Página