To get/detect browser name and version in Angular apps; Through this tutorial, i am going to show you easy way on how to detect or get browser name, version and type in angular apps.
Angular Detect Browser Name and Version Tutorial with Example
Follow the below given steps to get or detect browser name and version in angular apps:
- Step 1 – Create New Angular App
- Step 2 – Update app.Component ts File
- Step 3 – Show Browser Name and Version in HTML
- Step 4 – Start the Angular App
Step 1 – Create New Angular App
Run the following command on command prompt to install angular app:
ng new my-new-app
Step 2 – Update app.Component ts File
Then go to src/app directory and open app.component.ts. Then add the following code into component.ts file:
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { browserName = ''; browserVersion = ''; ngOnInit() { this.browserName = this.detectBrowserName(); this.browserVersion = this.detectBrowserVersion(); } detectBrowserName() { const agent = window.navigator.userAgent.toLowerCase() switch (true) { case agent.indexOf('edge') > -1: return 'edge'; case agent.indexOf('opr') > -1 && !!(<any>window).opr: return 'opera'; case agent.indexOf('chrome') > -1 && !!(<any>window).chrome: return 'chrome'; case agent.indexOf('trident') > -1: return 'ie'; case agent.indexOf('firefox') > -1: return 'firefox'; case agent.indexOf('safari') > -1: return 'safari'; default: return 'other'; } } detectBrowserVersion(){ var userAgent = navigator.userAgent, tem, matchTest = userAgent.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || []; if(/trident/i.test(matchTest[1])){ tem = /\brv[ :]+(\d+)/g.exec(userAgent) || []; return 'IE '+(tem[1] || ''); } if(matchTest[1]=== 'Chrome'){ tem = userAgent.match(/\b(OPR|Edge)\/(\d+)/); if(tem!= null) return tem.slice(1).join(' ').replace('OPR', 'Opera'); } matchTest= matchTest[2]? [matchTest[1], matchTest[2]]: [navigator.appName, navigator.appVersion, '-?']; if((tem= userAgent.match(/version\/(\d+)/i))!= null) matchTest.splice(1, 1, tem[1]); return matchTest.join(' '); } }ʼ’
Step 3 – Show Browser Name and Version in HTML
Go to src/app/ directory and open app.component.html and update the following code into it:
<div class="container mt-5"> <h2>Angular Display Browser Name and Version Example</h2> <table class="table table-striped mt-5"> <thead> <tr> <th>Browser Name</th> <th>Browser Version</th> </tr> </thead> <tbody> <tr> <td>{{ browserName | titlecase }}</td> <td>{{ browserVersion | titlecase }}</td> </tr> </tbody> </table> </div>
Step 4 – Start the Angular App
Execute the following command on the terminal to start angular app:
ng serve
Open the browser and type the given url then hit enter to run the app:
http://localhost:4200