0

I want to build my angular app for production using

npm run build:ssr

SSR is for server-side rendering. But after build when I try to run my project it gives an error in my header components

Document is not defined

header.ts

mobileMenu() {
    const mobileMenu = document.querySelector(".mobileHeader");
    mobileMenu.classList.toggle("stickymobile");
    const hambar = document.querySelector(".icon>i");
    mobileMenu.classList.toggle("move");
    const icon = document.querySelector(".icon");
    icon.classList.toggle("open");
  }

 head() {
    const image = document.querySelector(".image>img");
    window.addEventListener("scroll", (e) => {
      const header = document.querySelector(".desktopHeader");
      if (window.pageYOffset > 25) {
        header.classList.add("sticky");
        //@ts-ignore
        image.src = "../../../assets/Logo/Dark logo.svg";
      } else {
        header.classList.remove("sticky");
        //@ts-ignore
        image.src = "../../../assets/Logo/New logo.svg";
      }
    });
  }

  ngOnInit(): void {}

  ngAfterViewInit(): void {
    this.head();
  }

How to resolve this error, please help

sabban
  • 131
  • 5

1 Answers1

0

When you use Server side rendering you need to code being carefully with your code. Because some things changes when you code run in the server. Some of those things are the realted browser objects such as Document, window, etc and some functions such as SetTimeout and SetInterval. Those objects and functions does not exist in the server. So you need to avoid executon of some code when you are in the server and this is an example

import { Inject, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';

  constructor(@Inject(PLATFORM_ID) platformId: Object) {
    this.isPlatFormBrowser = isPlatformBrowser(platformId);
  }



  mobileMenu() {
    if(!this.isPlatFormBrowser) return;
      // now when you are in the server this code does not be executed although in the browser it does
    const mobileMenu = document.querySelector(".mobileHeader");
   //rest of your code here...
  }


  head(){
    if(!this.isPlatFormBrowser) return;
      // now when you are in the server this code does not be executed although in the browser it does
    window.addEventListener("scroll", (e) => {
    //rest of your code here...
  }
Manuel Panizzo
  • 876
  • 3
  • 8