detect browser and 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 Platform Module inside the module where you are going to implement browser specific feature (app.module.ts as 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 and check the appropriate field. As 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 device OS is Android
IOSIf device OS is IOS
FIREFOXIf it is a browser Firefox
BLINKIf it is a browser Chrome
WEBKITIf it is WebKit based browsers (Opera)
TRIDENTIf it is a browser IE 💩
EDGEIf it is a browser Microsoft EDGE (a bit better but still 💩)
———–———————————————————-
Note! Since version 79 EDGE uses 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.

About the author

Dmytro Mezhenskyi

I am a frontend developer with focus on Angular. Also YouTuber and instructor on Udemy and SkillShare.

1 Comment

Leave a Reply to Esoverof Cancel reply

Tags

Dmytro Mezhenskyi

I am a frontend developer with focus on Angular. Also YouTuber and instructor on Udemy and SkillShare.

Get in touch