both ngOnDestroy and DestroyRef serve the purpose of executing cleanup logic before an Angular component or destroyed, but they do so in different ways.
Key Differences
- Implementation:
- ngOnDestroy: This is a lifecycle hook method that be implemented in a component or directive class. it requires you to manully handle cleanup tasks, such as unsubscribing from observables.
- DestroyRef: Introduced in Angular 16, this is an injectable class that allow you to register cleanup callbacks using the
onDestorymethod. This can be done anywhere within the component’s context, not just in a specific lifecycle method.
- Flexibility:
- ngOnDestroy: Tied to the component lifecycle, making it less flexible for reusable logic across different components.
- DestroyRef: Offers greater flexibility as it can be injected and used to create reusable cleanup functions that can be shared across multiple components.
- Execution Order:
- If both are used in the same component,
ngOnDestroywill execute before any callbacks registered withDestroyRef.onDestroy().
- If both are used in the same component,
Example Comparison
Using ngOnDestroy:
ngOnDestroy() {
clearInterval(this.interval); // Cleanup logic
}
Using DestroyRef:
constructor(destroyRef: DestroyRef) {
destroyRef.onDestroy(() => {
clearInterval(this.interval); // Cleanup logic
});
}