Angular 17 window not defined

4.2k Views Asked by At

Recently after updating my angular cli from 16 to 17 I have been facing performance issues and I had no idea what is SSR and prerendering so I left them enabled. But the root cause was ssr.

  • After installing materialize-css I was getting an error M is not defined. Then I imported it from materialize-css.

  • Again I was getting an error window is not defined

4

There are 4 best solutions below

0
On BEST ANSWER

I disabled SSR in my angular.json

"server": "src/main.server.ts",
            "prerender": true,
            "ssr": {
              "entry": "server.ts"
            }

to

"server": "src/main.server.ts",
              "prerender": false,
              "ssr": false
1
On

When using Server side rendering (SSR) and/or prerendering, the app will run on a node environment where the global window object isn't defined.

If you want to keep using SSR/prenrender and still access window you can use afterNextRender() which will be invoked on the browser side only (the callback will be run outside the Angular zone, you also might need ngZone.run().)

1
On

I was getting the same error in Angular 17.

This solution worked for me:

if (typeof window !== "undefined") {
   // browser code
}

Source: https://dev.to/vvo/how-to-solve-window-is-not-defined-errors-in-react-and-next-js-5f97 Author: Vincent Voyer

0
On

I had the same problem and worked around the problem by using ChangeDetectorRef:

export class ApplicationLayoutComponent implements OnInit {
  screenWidth!: number;
  injector = inject(Injector);
  @ViewChild('sidebar') sidebar!: ElementRef;

  @HostListener('window:resize', ['$event'])

  onResize(event: Event) {
    this.screenWidth = window.innerWidth;
  }

  constructor(private cd : ChangeDetectorRef) {
    
  }
  ngOnInit(): void {
    afterNextRender(() => 
      this.changeScreenWidth(),
      {injector: this.injector, phase: AfterRenderPhase.Read}          
    );
  }

  changeScreenWidth() {
    this.screenWidth = window.innerWidth;    
    this.cd.detectChanges();
  }