Open In App

What is the Purpose of base href Tag in Angular ?

Last Updated : 26 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see what is base href tag in Angular, along with understanding their basic implementation with the help of examples.

Base href Tag

The base href is important for generating correct routes, in -case you are deploying your project in a subfolder. The base href element has the angular router to compose the navigation URLs. The base href tells the browser where actually the script files will execute and it helps the router to compose a navigation URL. A relative base URL helps in indexing better on the website server or on the working local website copy.

By default, the value is set to be “/” i.e root which means the scripts are in root the directory. The base href is mentioned in the index.html file within the <head></head> tags. 

 

Syntax:

<base href=""/>

Example 1: In this example, we will see when we have just mentioned the base href=”/”. This is the default case, for this, all the navigation URLs will be relative to the root of the application, i.e. any further path will be appended to the root URL.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <base href="/">
</head>
  
<body>
    <div style="text-align: center;">
        <h1 style="color:green">GeeksforGeeks</h1>
        <h3>What is the purpose of base href tag?</h3>
        base href="/"
    </div>
</body>
  
</html>


Output:

20230627_224221.gif

Example 2: In this example, we are setting a value to the base href that is “/home”, now any new path we are adding to it gets appended to the set base href value.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <base href="/home/">
</head>
  
<body>
    <div style="text-align: center;">
        <h1 style="color:green">GeeksforGeeks</h1>
        <h3>What is the purpose of base href tag?</h3>
        base href="/home/"
    </div>
</body>
  
</html>


Run the command: Now to the Angular CLI or terminal, set the below command to set the base href value so that, you get to see how the navigation will look after setting different values to the base -href.

ng serve --serve-path home

Output: You can see in this example, any new path we are adding gets appended to the base href.

20230627_222531.gif



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads