Skip to content

Instantly share code, notes, and snippets.

@dmorosinotto
dmorosinotto / base.component.ts
Last active May 31, 2022 13:03
Angular BaseComponent with handle destroy$ and takeUntil pattern to unsubscribe!
import { Directive, OnDestroy } from "@angular/core";
import { Subject } from "rxjs";
import { takeUntil } from "rxjs/operators";
@Directive() // Needed only for Angular v9+ strict mode that enforce decorator to enable Component inheritance
export abstract class BaseComponent implements OnDestroy {
// _destroy$ is LAZY: it'll be created (and allocate memory) only if you use takeUntilDestroy
private _destroy$?: Subject<void>;
protected takeUntilDestroy = <T>() => {
if (!this._destroy$) this._destroy$ = new Subject<void>(); // LAZY Subject