Adding NGUniversal to my app stopped several things from functioning

51 Views Asked by At

I added Angular Universal to my Angular 16 app and ran npm run dev:ssr just to discover several parts of my application aren't functioning.

  1. None of my angular animations are working, as of right now I'm getting this error in my terminal

@pageAnimation has failed due to: NG03014: query(":enter, :leave") returned zero elements. (Use query(":enter, :leave", { optional: true }) if you wish to allow this.)

This particular animation is for the page transitions but I also have have a navbar at the top that slides down as the user scrolls along with a sidebar that slides in when the user clicks the hamburger menu in the top nav bar, neither of which work.

  1. None of my routerLinks work anywhere on the site. I can navigate to different pages by typing the path in the address bar but clicking the links has no effect whatsoever.

  2. None of my buttons work in the application. I created lots of control panels / dashboards with buttons that toggle different views with the *ngIf directive and none of them do anything.

  3. I embed components into a resizable <iframe> component I built to demonstrate responsiveness. None of those components embed into the .

  4. I built a component that uses highlight-js to show code snippets on my site. I store the snippets in a string variable on the parent component and pass them into the snippet component through an @Input which then passes it into the template. All I see in my app are empty black boxes because the code snippets aren't being passed into the component for some reason.

  5. I use the ResizeObserver API to watch the size of the <iframe> as the user scales it up and down. The variables I store the new values to don't update as I scale the <iframe>.

I know these problems are occurring because certain browser objects aren't available on the server and have come across a few solutions people employed to resolve their issues however they haven't worked for me. I tried injecting PLATFORM_ID into my app.component.ts file but that didn't make a difference. I even imported the afterRender() method and ran it in my constructor however that doesn't seem to do anything either as I did a console.log() inside the callback I pass into it just to see if it was doing anything and nothing logged to the console.

I'm using all standalone components with no app.module file so I had to figure out on my own how to get everything setup to work however maybe I'm doing something wrong. My files look like this:

main.ts

import { provideAnimations } from '@angular/platform-browser/animations';
import { ApplicationConfig } from '@angular/core';
import { provideRouter, withInMemoryScrolling } from '@angular/router';
import { SITEROUTES } from './app/routes';
import { HIGHLIGHT_OPTIONS, HighlightOptions } from 'ngx-highlightjs';
import { provideClientHydration } from '@angular/platform-browser';

export const appConfig: ApplicationConfig = {
  providers: [
    provideClientHydration(),
    provideRouter(SITEROUTES, withInMemoryScrolling({scrollPositionRestoration: 'enabled'})),
    provideAnimations(),
    {
      provide: HIGHLIGHT_OPTIONS,
      useValue: <HighlightOptions>{
        coreLibraryLoader: () => import('highlight.js/lib/core'),
        lineNumbersLoader: () => import('ngx-highlightjs/line-numbers'),
        languages: {
          xml: () => import('highlight.js/lib/languages/xml'),
          css: () => import('highlight.js/lib/languages/css')
        },
        themePath: '../node_modules/highlight.js/styles/a11y-dark.css'
      }
    }
  ]
};

main.server.ts

import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { config } from './app/app.config.server';

const bootstrap = () => bootstrapApplication(AppComponent, config);

export default bootstrap;

app.config.server.ts

import { mergeApplicationConfig, ApplicationConfig } from '@angular/core';
import { provideServerRendering } from '@angular/platform-server';
import {appConfig} from '../main';

const serverConfig: ApplicationConfig = {
  providers: [
    provideServerRendering()
  ]
};

export const config = mergeApplicationConfig(appConfig, serverConfig);

server.ts

import 'zone.js/node';

import { APP_BASE_HREF } from '@angular/common';
import { ngExpressEngine } from '@nguniversal/express-engine';
import * as express from 'express';
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import bootstrap from './src/main.server';

// The Express app is exported so that it can be used by serverless Functions.
export function app(): express.Express {
  const server = express();
  const distFolder = join(process.cwd(), 'dist/srcry-documentation/browser');
  const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index';

  // Our Universal express-engine (found @ https://github.com/angular/universal/tree/main/modules/express-engine)
  server.engine('html', ngExpressEngine({
    bootstrap
  }));

  server.set('view engine', 'html');
  server.set('views', distFolder);

  // Example Express Rest API endpoints
  // server.get('/api/**', (req, res) => { });
  // Serve static files from /browser
  server.get('*.*', express.static(distFolder, {
    maxAge: '1y'
  }));

  // All regular routes use the Universal engine
  server.get('*', (req, res) => {
    res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
  });

  return server;
}

function run(): void {
  const port = process.env['PORT'] || 4000;

  // Start up the Node server
  const server = app();
  server.listen(port, () => {
    console.log(`Node Express server listening on http://localhost:${port}`);
  });
}

// Webpack will replace 'require' with '__webpack_require__'
// '__non_webpack_require__' is a proxy to Node 'require'
// The below code is to ensure that the server is run only when not requiring the bundle.
declare const __non_webpack_require__: NodeRequire;
const mainModule = __non_webpack_require__.main;
const moduleFilename = mainModule && mainModule.filename || '';
if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
  run();
}

export default bootstrap;

tsconfig.server.json

/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
  "extends": "./tsconfig.app.json",
  "compilerOptions": {
    "outDir": "./out-tsc/server",
    "types": [
      "node"
    ]
  },
  "files": [
    "src/main.server.ts",
    "server.ts"
  ]
}

Does anybody see what the problem is? Am I missing something in one of these files? Let me know if there's anything else you need to see and I'll update the post with the code.

0

There are 0 best solutions below