How to Get Domain Name in Angular App?

By Hardik Savani May 9, 2022 Category : Angular

Hi,

Are you looking for example of angular get domain name. if you want to see example of how to get domain name in angular then you are a right place. Here you will learn angular universal get domain name. I’m going to show you about angular get domain name using DOCUMENT. Let's see bellow example angular get document location hostname.

In this example, I will show you how to get a domain name in an angular application. we will use Inject, Injectable and DOCUMENT to get document.location 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 and angular 13 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 {

domain = '';

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

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

constructor

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

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

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

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

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

ngOnInit

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

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

ngOnInit() {

this.domain = this.document.location.hostname;

console.log(this.domain);

}

}

Output:

localhost

I hope it can help you...

Tags :