If you are using angular need to access to DOM with SSR, then use domino package.
Domino provide support for the DOM API and also CSS for querySelector(), querySelectorAll(), and matches().
Install domino from your terminal.
npm install domino --save
Add angular universal in your app.
ng add @nguniversal/express-engine
Edit the server.ts file and add the following lines, for configure it create "document" object and "window" as global.
const domino = require('domino');
const fs = require('fs');
const path = require('path');
// Use the browser index.html as template for the mock window
const template = fs
.readFileSync(path.join(join(process.cwd(), 'dist/yourprojectname/browser'), 'index.html'))
.toString();
// Shim for the global window and document objects.
const window = domino.createWindow(template);
global['window'] = window;
global['document'] = window.document;
If you to copy and paste, please change the project name.
Keep in mind change for server side render the build command is build:ssr and need to publish browser directory.
npm run build:ssr
dist/yourprojectname/browser
Photo by Charl Folscher on Unsplash
Top comments (4)
Where should I add these lines? I tested it in all of the server.ts scopes, but I get "ReferenceError: window is not defined" in all cases.
Is anything wrong with this line?:
global['window'] = window;
very helpful! thanks!
I have tried domino , but we are getting “Not yet Implemented” message
And
Event is undefined
Please paste more details to try help u