Destroy components if out of viewport when using the @defer angular block

300 Views Asked by At

I'm using the new Angular @defer block, which looks great. But in the same way that I can defer until the component enters the viewport, I wanted it to destroy the component when it gets out.

What I want is to implement a virtual scroller that not only inserts component into the view but also destroy them when it goes out. So it would be able to render over 1000 heavy components with no problem. Here is the code:

@for (item of items; track item.id) {
  <div #container [style.height.px]="500">
    @defer (on viewport(container)) {
      <app-item [item]="item" />
    }
  </div>
}

Is there an "angular way" to do that?

-- Edit --

I don't mean that the @defer block doesn't work, because it does and it's awesome! The purpose of this question is just to know if using the @defer is possible to only render the content when it's in the viewport.

It would also be very useful for very expensive components because you would be able to destroy them when they are out of the viewport, saving the browser processing.

1

There are 1 best solutions below

2
On

As you may already know, defer simply postpones the loading of the component until the specified time or event. When it gets loaded, it means it has completed its own task.

If it could destroy the templates when they exit the viewport, it would be called Virtual Scroll. Defer is yet to provide sufficient functionality for building it.

Therefore, You need to build your own Virtual Scroll by inspiring the existing ones like Angular CDK or you can use it directly in your project if it is installed.