In this article, we are going to explore the device detection library 'ngx-device-detector' in the angular application.
The output from the mobile
An Overview On ngx-device-detector Library:
This library is useful to identify a browser, device type, request user agent, etc. This library is also compatible with the angular AOT compiler.
Library provides us angular injectable service like 'DeviceDetectorService'. This service provides methods like:
- getDeviceInfo
- isMobile
- isTablet
- isDesktop
Create A Sample Angular Application:
Let's create a sample angular application to understand the 'ngx-device-detector' library.
Command To Install Angular CLI:(If not installed on your system previously)
npm install -g @angular/cli
Angular CLI Command To Create Angular App: ng new your_project_name
Command To Run App:
ng serve
Install Device Detection Npm Package:
Command To Install Device Detection Package
npm install ngx-device-detector --save
After installing npm package reference will be automatically added to the package.json file.Check Device Detection:
Let's write a sample code that will give full information on the device
src/app/app.component.ts:
import { Component, OnInit } from '@angular/core'; import { DeviceDetectorService, DeviceInfo } from 'ngx-device-detector'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent implements OnInit { deviceInfo:DeviceInfo; title = 'device-detection-sample'; constructor(private deviceDetectorService: DeviceDetectorService) {} ngOnInit(): void { this.deviceInfo = this.deviceDetectorService.getDeviceInfo(); } }
- (Line: 13) The 'DeviceDetectorService' provided by the 'ngx-device-detector' injected into our component.
- (Line: 15) The 'DeviceDetectorService' provides a method 'getDeviceInfo' this method returns of type 'DeviceInfo' interface where it provides all the information of our device.
<div> <ul> <li>user Agent - {{deviceInfo.userAgent}}</li> <li>Os - {{deviceInfo.os}}</li> <li>browser - {{deviceInfo.browser}}</li> <li>device - {{deviceInfo.device}}</li> <li>os_version - {{deviceInfo.os_version}}</li> <li>browser_version - {{deviceInfo.browser_version}}</li> <li>deviceType - {{deviceInfo.deviceType}}</li> <li>orientation - {{deviceInfo.orientation}}</li> </ul> </div>
- Here all the properties are derived from the 'DeviceInfo' interface.
The output from the mobile
When Library Useful:
- Tracking the user's devices, browser names
- To dynamically render the angular components based on the browser type.
- To identify the browser-specific errors, to know from which browser are happening.
Support Me!
Buy Me A Coffee
PayPal Me
Wrapping Up:
Hopefully, I think this article delivered some useful information about device detection in angular application. I love to have your feedback, suggestions, and better techniques in the comment section below.
Comments
Post a Comment