Angular2 how to set app root path independently from html base url

jdachtera picture jdachtera · Oct 12, 2016 · Viewed 28.3k times · Source

I'm building an angular2 application/widget that will be embedded into TYPO3 as a plugin that can be inserted on any content page. This means it could end up at different root paths e.g.:

/page1/app
/page/subpage/subpage/whatever

The global base url (base href=..) is already set by TYPO3 and can't be changed. How can I give angular some kind of root prefix so that it can build up its routes correctly?

I'm using the new router as documented here: https://angular.io/docs/ts/latest/guide/router.html

Answer

jdachtera picture jdachtera · Oct 20, 2016

Actually there is a solution in the angular docs but it's pretty hard to find. It's possible to set the base url in angular without using a <base> tag.
So you just have to set the base url to a global JavaScript variable using fluid and then provide it to angular in the app module.

Fluid:

<script>
   var app_base_url = '<f:uri.page pageUid="{currentPageUid}" />';
</script>

Angular:

declare var app_base_url;

import {Component, NgModule} from '@angular/core';
import {APP_BASE_HREF} from '@angular/common';
@NgModule({
  providers: [{provide: APP_BASE_HREF, useValue:app_base_url}]
})
class AppModule {}

https://angular.io/docs/ts/latest/api/common/index/APP_BASE_HREF-let.html