Menu Close

How to set base href dynamically with Angular?

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.

Posted in Angular, Angular Answers