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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With