2

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')`;
}
Chris Barr
  • 29,851
  • 23
  • 95
  • 135
  • maybe you can skip executing this code using `@Inject(PLATFORM_ID) platformId` and checking whether it is server with `if (isPlatformServer(platformId)) {.... skip setting BG image}` – Maksat Rahmanov Jul 18 '23 at 13:03
  • That might just work! Thanks. Another possible option is that `this.document.defaultView?.navigator.userAgent` is an empty string when prerendering – Chris Barr Jul 18 '23 at 13:08
  • @MaksatRahmanov That's absolutely the easiest way to do this, thank you. If you make an answer for that I will mark is as accepted. – Chris Barr Jul 18 '23 at 13:29
  • You need to use the `TransferState` service – Pieterjan Jul 26 '23 at 10:54

1 Answers1

2

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 }

Maksat Rahmanov
  • 377
  • 3
  • 10