Unlock the Power of On-Demand Rendering in Angular!

Luka Onikadze
3 min readJul 31, 2023
Cover image

Introduction:

With the ever-increasing demands for performant web applications, developers continuously seek techniques to optimize rendering. One such approach is conditional rendering based on visibility within the viewport. This article introduces an Angular component, ViewportRender, that only initializes and renders its content when it enters the viewport.

Creating the ViewportRender Component

import { Component, OnInit, OnDestroy, ViewChild, TemplateRef, ViewContainerRef, ElementRef, ContentChild } from '@angular/core';

@Component({
selector: 'viewport-render',
template: `
<div #sentinel class="sentinel"></div>
<ng-container #container></ng-container>
`,
styles: [`
.sentinel {
width: 1px;
height: 1px;
opacity: 0;
position: absolute;
}
`]
})
export class ViewportRenderComponent implements OnInit, OnDestroy {

private intersectionObserver: IntersectionObserver;

@ViewChild('container', { read: ViewContainerRef, static: true }) container: ViewContainerRef;
@ViewChild('sentinel', { static: true }) sentinel: ElementRef;
@ContentChild(TemplateRef, { static: false }) template: TemplateRef<any>;

constructor() {}

ngOnInit() {
this.intersectionObserver = new IntersectionObserver(entries => {
if…

--

--

Responses (1)