Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 17 window not defined

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

like image 658
Abrar Avatar asked Jun 09 '26 22:06

Abrar


2 Answers

You can also create a token for the window, just as Angular does for the Document:

import { InjectionToken } from '@angular/core';

export const WINDOW = new InjectionToken<Window>('WindowToken', {
  factory: () => {
    if(typeof window !== 'undefined') {
      return window
    }
    return new Window(); // does this work?
  }
});

Then you can inject it in the places you need the window object like so:

@Component({
  selector: 'my-component',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './my-component.component.html',
  styleUrl: './my-component.component.scss',
})
export class RegistrationFormComponent {
  private _window = inject(WINDOW); // or window = inject(WINDOW);

  inSomeFunction() {
    this._window.location.assign('my.url')
  }
}

This way, you can keep the benefits of SSR and prerendering and use the window object.

like image 102
Safe Avatar answered Jun 11 '26 11:06

Safe


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

like image 21
LaMaga Avatar answered Jun 11 '26 13:06

LaMaga