Categories
Angular Answers

How to set base href dynamically with Angular?

Spread the love

Sometimes, we want to set base href dynamically with Angular.

In this article, we’ll look at how to set base href dynamically with Angular.

How to set base href dynamically with Angular?

To set base href dynamically with Angular, we can add an entry to the providers array in NgModule.

For instance, we write

import { APP_BASE_HREF } from "@angular/common";
import { NgModule } from "@angular/core";

@NgModule({
  providers: [
    {
      provide: APP_BASE_HREF,
      useValue: "/" + (window.location.pathname.split("/")[1] || ""),
    },
  ],
})
export class AppModule {}

to call @NgModule with an object that has the providers property.

In the providers array, we add an entry to set the base element’s href attribute dynamically with

{
   provide: APP_BASE_HREF,
   useValue: "/" + (window.location.pathname.split("/")[1] || ""),
}

We set the base element’s href attribute to the value of useVale.

Conclusion

To set base href dynamically with Angular, we can add an entry to the providers array in NgModule.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *