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

How often do you need to fix some bug or implement some feature for some specific browser or operating system like iOS / Android? I am quite sure that it happens very often. And also very often developers use different hacks for it or reinvent the wheel.

The truth is that the Angular team has done it already for you many years ago and included it in Angular CDK (Component Development Kit), so you should not write the logic from scratch but just re-use the logic.

If you are not using Angular CDK yet – you need just install it, so just navigate in your Terminal to the root folder of your project and run the next command:

ng add @angular/cdk

Once you have done it you need to import the Platform Module inside the module where you are going to implement browser-specific feature (app.module.ts as an example)

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


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

And now you can inject the Platform service into any component where you need it and check the appropriate field. As an example like this:

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!');
    }
  }
}

And that’s it! It is very simple!

There is a list of all available platform values:

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

Alright, guys, that’s it! As you can see it is very easy. If you prefer video format you can see my video dedicated to this topic.

Advanced Angular Forms – Deep Dive


Check out the most Advanced Angular Forms course made by Google Developer Expert in Angular

About the author

Dmytro Mezhenskyi

Google Developer Expert in Angular | YouTube Content Creator | Instructor in Web Development

5 Comments

Leave a Reply to Pere Cancel reply

Tags

Dmytro Mezhenskyi

Google Developer Expert in Angular | YouTube Content Creator | Instructor in Web Development

Get in touch