Search code examples
windowsangulartypescriptnavigator

How to fetch the device information using Angular2 and Typescript


I have a table, I need to fill these details into my table from typescript.

1.Device Name
2. Device OS
3. Location
4. Browser
5. IsActive

These fields must be filled from typescript, so can anyone help me to solve this


Solution

  • You can use, ngx-device-detector

    ngx-device-detector is An Angular 2 (and beyond) powered AOT compatible device detector that helps to identify browser, os and other useful information regarding the device using the app. The processing is based on user-agent.

    Installation:

    To install this library, run:

    $ npm install ngx-device-detector --save
    

    Usage:

    Import DeviceDetectorModule in your app.module.ts
    
      import { NgModule } from '@angular/core';
      import { DeviceDetectorModule } from 'ngx-device-detector';
      ...
      @NgModule({
        declarations: [
          ...
          LoginComponent,
          SignupComponent
          ...
        ],
        imports: [
          CommonModule,
          FormsModule,
          DeviceDetectorModule.forRoot()
        ],
        providers:[
          AuthService
        ]
        ...
      })
    

    In your component where you want to use the Device Service

    import { Component } from '@angular/core';
      ...
      import { DeviceDetectorService } from 'ngx-device-detector';
      ...
      @Component({
        selector: 'home',  // <home></home>
        styleUrls: [ './home.component.scss' ],
        templateUrl: './home.component.html',
        ...
      })
    
      export class HomeComponent {
        deviceInfo = null;
        ...
        constructor(..., private http: Http, private deviceService: DeviceDetectorService) {
          this.epicFunction();
        }
        ...
        epicFunction() {
          console.log('hello `Home` component');
          this.deviceInfo = this.deviceService.getDeviceInfo();
          console.log(this.deviceInfo);
        }
        ...
      }
    

    Device service:

    Holds the following properties:

    • browser
    • os
    • device
    • userAgent
    • os_version