Angular Get Current Used Port Number Example

By Hardik Savani May 2, 2024 Category : Angular

Hello,

In this quick example, let's see angular get current used port number. let’s discuss about how to get port number in angular. I’m going to show you about angular get current running port. I would like to show you angular get port number using DOCUMENT. Alright, let’s dive into the steps.

In this example, I will show you how to get a port number in an angular application. we will use Inject, Injectable and DOCUMENT to get document.port details. so let's see below ts file which you can use in your service file as well.

You can use this example with angular 8, angular 9, angular 10, angular 11, angular 12, angular 13, angular 14, angular 15, angular 16 and angular 17 version.

Let's see bellow example with output:

src/app/app.component.s

import { Component, OnInit, Inject, Injectable } from '@angular/core';

import { DOCUMENT } from '@angular/common';

@Component({

selector: 'app-root',

templateUrl: './app.component.html',

styleUrls: ['./app.component.css']

})

export class AppComponent implements OnInit {

port = '';

/*------------------------------------------

--------------------------------------------

constructor

--------------------------------------------

--------------------------------------------*/

constructor(@Inject(DOCUMENT) private document: any) { }

/*------------------------------------------

--------------------------------------------

ngOnInit

--------------------------------------------

--------------------------------------------*/

ngOnInit() {

this.port = this.document.location.port;

console.log(this.port);

}

}

Output:

4200

I hope it can help you...

Tags :
Shares