12

In the past you could use isBrowser from Angular Universal to check if your page was rendering in a browser (and therefore you can use things like localStorage) or if it was doing server side pre-rendering.

But it seems that angular2-universal was dissolved into @angular/core, @angular/platform-server and @angular/platform-browser.

I've looked for similar functionality in the API documentation for Angular 4 and also tried to find it somewhere in the source code, but without luck.

Am I missing something or what is the Angular 4 way of checking if the rendering is running in a browser? Or should I simply just check if window is defined?

Staeff
  • 4,994
  • 6
  • 34
  • 58
  • 1
    isPlatformBrowser() - https://stackoverflow.com/a/43619639/7974050 – Amit Kumar Singh Sep 07 '17 at 15:05
  • Possible duplicate of [error using isBrowser function in angular universal](https://stackoverflow.com/questions/43586005/error-using-isbrowser-function-in-angular-universal) – Surreal Sep 07 '17 at 15:20

3 Answers3

31
import { PLATFORM_ID, Inject } from '@angular/core';
import { isPlatformBrowser} from '@angular/common';
...
export class MyComponent {
...
    testBrowser: boolean;
    constructor(
        @Inject(PLATFORM_ID) platformId: string) {
            this.testBrowser = isPlatformBrowser(platformId);
            if (this.testBrowser) {
                //this is only executed on the browser
            }
    }
...
anode7
  • 376
  • 2
  • 7
3

You can import isPlatformBrowser(<platform id>) as so:

import { isPlatformBrowser } from '@angular/common';

and that will allow you to check for whether it is rendering in browser or not.

As a note, there is also a isPlatformServer in @angular/common as well.

jpwiddy
  • 140
  • 1
  • 7
0

Do the Following steps:

import { isPlatformBrowser } from '@angular/common';
import { Inject, PLATFORM_ID } from '@angular/core;

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

I hope it helps:

Abhinav Akhil
  • 173
  • 1
  • 7