Identifying the Browser and Mobile OS with Angular CDK's Platform Module

How frequently do you encounter a bug or need to roll out a feature that targets a particular browser or operating system such as iOS or Android? It probably happens a lot. In many cases, developers resort to hacks or end up duplicating existing solutions.

The good news is that the Angular team built this functionality into the Angular CDK (Component Development Kit) long ago. There's no need to create the logic from scratch—you can simply leverage the built-in tooling.

If Angular CDK isn't part of your project yet, installation is straightforward. Open your Terminal, go to the project's root directory, and run:

ng add @angular/cdk

After installation, import the PlatformModule into the module where you’ll implement the browser-specific behavior. For instance, that would be app.module.ts:

// ... some other imports
import {PlatformModule} from '@angular/cdk/platform';


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    // ... other modules
    BrowserModule,
    PlatformModule // <-- Import here
  ],
})
export class AppModule { }

Now, you can inject the Platform service into any component that needs it and check the relevant property. Here’s an example:

import {Component} from '@angular/core'; 

@Component({
  selector: 'some-component',
  templateUrl: 'some-component.html'
})
export class SomeComponent {
  constructor(public platform: Platform) {
    if (this.platform.IOS) {
      console.log('this is IOS device!');
    }
  }
}

That’s all there is to it—it’s that simple.

The full set of available platform values is listed below:

ANDROIDIf the device OS is Android
IOSIf the device OS is IOS
FIREFOXIf it is a browser Firefox
BLINKIf it is a browser Chrome
WEBKITIf it is WebKit-based browser (Opera)
TRIDENTIf it is a browser IE 💩
EDGEIf it is a browser Microsoft EDGE
———–———————————————————-
Note! Since version 79 EDGE uses the Blink browser engine, so this option works only for old EDGE versions.
SAFARIIf it is a browser Safari
List of available options for Platform Service

Advanced Angular Forms – Deep Dive

That covers the essentials. If you prefer a video walkthrough, I have one dedicated to this subject.

detect the browser and Mobile OS with Angular CDK – Platform module — figure 1

Be sure to check out the most Advanced Angular Forms course by a Google Developer Expert in Angular.