Discover the New Angular 16 Feature - DestroyRef

Angular is a popular open-source framework for building web applications. It provides a robust and efficient structure for developing complex and dynamic front-end applications. The framework has various features that make it a preferred choice among developers, such as two-way data binding, dependency injection, and modular architecture.

In the latest version of Angular, which is version 16, a new provider called `DestroyRef` has been introduced. This provider offers developers an easy way to register destroy callbacks for a particular lifecycle scope. The lifecycle scope refers to the different stages of an Angular application's lifecycle, such as the creation, rendering, and destruction of components.

The `DestroyRef` provider allows developers to register callbacks that are executed when a particular lifecycle scope is destroyed. This feature is highly beneficial for managing resources and cleaning up the application's memory. It is applicable to various entities such as components, directives, pipes, embedded views, and instances of `EnvironmentInjector`.

Using `DestroyRef` in your Angular application is simple and straightforward. To register a destroy callback, all you need to do is inject the `DestroyRef` provider and follow these steps:

Step 1. Generate a util function that utilizes the DestroyRef

If you're familiar to `Subjects`, and using `takeUntil` from Rxjs - it will be really easy for you to understand the following code:

typescript
// utils/functions.ts
export function destroy() {
  const subject = new Subject();

  inject(DestroyRef).onDestroy(() => {
    subject.next(true);
    subject.complete();
  });

  return () => takeUntil(subject.asObservable());
}

The code above is creating a subject that will be completed whenever the component in destroyed by utilizing `inject`, `DestroyRef` from `@angular/core` and the `onDestroy` function.

Step 2. Apply the util function to simplify our life

To create reusable code and ensure that we're simplifying our lives of developers, we can easily apply the created function in one of our components by writing the following code:

typescript
@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss'],
})
export class TestComponent {
  private destroy$ = destroy();
  data = [];

  constructor(private dataService: DataService) {
    this.dataService
      .getAll()
      .pipe(this.destroy$())
      .subscribe((data) => {
        this.data = data;
      });
  }
}

The code above calls the getAll API to fetch data and is utilizing the `destroy$` function, which is returning the `takeUntil` operator we created in step 1. It will ensure that we unsubscribe to the subscription automatically when the component is destroyed. This is all done without having to handle the unsubscriptions within the component which will reduce the amount of boilerplate code that needs to be added.

In summary, the new `DestroyRef` provider in Angular version 16 offers developers a powerful tool to manage resources and clean up memory. It is applicable to various entities within an Angular application and can be used to register destroy callbacks for specific lifecycle scopes.

Check out the code on Github