Angular Universal SSR Cookbook

By

Angular Universal is a powerful tool that allows us to render our applications on the server, but it contains many pitfalls because NodeJS does not have the same APIs as the DOM. The snippet contains a collection of recipes to for common SSR use cases.

Work in Progress

This snippet is a work in progress. If you have a useful addition feel free to add it below by making a pull request on Github.

Platform Checking

In some cases, you may have code that should only run in the browser. You can do this by checking the platform and using conditional logic in your components.

file_type_ng_component_ts some.component.ts
import { Component, Inject } from '@angular/core';
import { PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';

@Component(...)
export class SomeComponent {
  isBrowser: boolean;

  constructor( @Inject(PLATFORM_ID) platformId) {
    this.isBrowser = isPlatformBrowser(platformId);
  }
}

file_type_html foo.component.html
<button *ngIf="isBrowser">
   <!-- Only show on browsers -->
</button>

Q&A Chat