Accessing the DOM in Angular Universal

Angular-Universal (or Server-Side Angular) has been officially adopted Angular. Most of the core functionality of universal can be found in the module platform-server. This means for those us who are stuck with old universal-starter-code repos, the upgrade will be a little like this:

One update I found confusing, was how to utilize the new PLATFORM_ID along with checking if the PLATFORM_ID was on the browser or server using isPlatformBrowser and isPlatformServer.

The Old Way (sigh, the good ole’ days)

import { isBrowser, isNode } from 'angular2-universal';
....
constructor(){}

ngOnInit(){
  if(isNode){
    this._optimizelyService.variation.then(variation => {
      if (variation === 'varA') {
        this.color = 'blue';
      }
    });
  }
}

getTodos() {
  if(isBrowser){
    if(localStorage.getItem('todos')){
      // do something
    }
  }
}

The Change

Now that Angular Universal has been merged into Angular 4, the way the DOM is accessed is by injecting the PLATFORM_ID into the constructor, then passing that into a call to either isPlatformBrowser or isPlatformServer

import { Component, OnInit, Inject, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser} from '@angular/common';
import { isPlatformServer } from '@angular/common';
....
constructor(@Inject(PLATFORM_ID) private platformId: Object){}

ngOnInit(){
  if(isPlatformServer(this.platformId)){
    this._optimizelyService.variation.then(variation => {
      if (variation === 'varA') {
        this.color = 'blue';
      }
    });
  }
}

getTodos() {
  if(isPlatformBrowser(this.platformId){
    if(localStorage.getItem('todos')){
      // do something
    }
}


Helpful Links

Angular 4 Upgrade Guide
Angular 4 Announcement
Angular 4 Upgrade Tool

Shoutout to the following for their Contributions to this post

Kevin Phelps
Twitter
Website

Praveen Rana
Twitter
Website

Cyrille Tuzi
Twitter
Website

Natasha Wahid
Twitter
Website
Example Page

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s