Search code examples
angularangular-universalangular-ssr

How to detect an Angular Universal prerender build?


I have an Angular 16 app that will select a random background image once when the app starts up, it works like this:

export class AppComponent implements OnInit {
  private readonly backgroundImagesCount = 8;

  constructor(@Inject(DOCUMENT) private readonly document: Document) {}

  ngOnInit(): void {
    const randomNum = Math.floor(Math.random() * this.backgroundImagesCount + 1);
    this.document.body.style.backgroundImage = `url('/assets/bg${randomNum}.jpg')`;
  }
}

I've just added Angular Universal to this app so it can prerender the routes. The problem is that the "random" background is now hard-coded into the prerendered HTML. When the app starts up you will briefly see the pre-selected "random" background flash, and then the actual angular app bootstraps and the real random background is selected.

How can I detect the prerendering in my application? Ideally I'd like to just skip this BG image stuff when prerendering but allow it to run once the app bootstraps. is there something I can use that can work like this pseudo-code below?

if(!isPrerendering){
  const randomNum = Math.floor(Math.random() * this.backgroundImagesCount + 1);
  this.document.body.style.backgroundImage = `url('/assets/bg${randomNum}.jpg')`;
}

Solution

  • You can skip executing some part of code by using @Inject(PLATFORM_ID) platformId

    Check whether code is currently running on server side with isPlatformServer() method from @angular/common package.

    if (isPlatformServer(platformId)) { .... skip setting BG image }