How to get IP Address in Angular?

In this blog, we are going to see that how can we get the IP Address in Angular.How to get IP Address in Angular?

We can get the current IP Address in angular 6, angular 7, angular 8, angular 9, angular 10, angular 11, angular 12, and angular 13.

Here, we will use IP Addresses in JSON.

First, create an Angular Application using Angular CLI and follow the below steps:

  1. Add a new angular service in your app using CLI with the following command:

ng g service IpService

2. Now, import HttpClientModule from “@angular/common/http” in the app.module.ts file to work with http:// services and can call API.

import { HttpClientModule } from “@angular/common/http”;

imports: [
HttpClientModule
]

Open your Service File and use the following code:

import { Injectable } from ‘@angular/core’;
import { HttpClient } from ‘@angular/common/http’;

@Injectable({
providedIn: ‘root’
})
export class IpServiceService {

constructor(private http:HttpClient) { }
public getIPAddress()
{
return this.http.get(“http://api.ipify.org/?format=json”);
}
}

Here, first, we imported HttpClient from @angular/common/http and injected a dependency in the service constructor. At last, we created a function named getIPAddress() from where we’ll return an Observable from here.

3. Now open your component file as we did in app.component.ts. Firstly, import and inject the service object in the component’s constructor and subscribe the getIpAddress() function from your service into a local variable, as in the following code:

import { Component, OnInit } from '@angular/core';  
import { IpServiceService } from './ip-service.service';  
  
@Component({  
  selector: 'app-root',  
  templateUrl: './app.component.html',  
  styleUrls: ['./app.component.css']  
})  
export class AppComponent implements OnInit {  
  constructor(private ip:IpServiceService){}  
  title = 'DemoApp';  
  ipAddress:string;  
ngOnInit()  
  {  
    this.getIP();  
  }  
  getIP()  
  {  
    this.ip.getIPAddress().subscribe((res:any)=>{  
      this.ipAddress=res.ip;  
    });  
  }  
}

Finally, open your app.component.html and try to print that variable using interpolation brackets.

<div class="container"> <p>Your IP Address : {{ipAddress}}</p> </div> 

4. Serve your angular app and open it in your browser to check the IP Address:

I hope you will follow the above steps and use this in your application.

So, thanks for following this blog, and if you need any help please leave your queries in the comment box we will be happy to help you.

How to get IP Address in Angular?