Wednesday, April 12, 2017

How do I change href generation in UI-Router for Angular 2?

Leave a Comment

I am trying to add subdomain support to UI-Router. Imagine these routes with custom attribute 'domain':

{ name: 'mainhome', url: '/', domain: 'example.com', component: 'MainSiteComponent' }, { name: 'bloghome', url: '/', domain: 'me.example.com', component: 'BlogComponent' }, 

NOTE: both routes have the same route url

I am trying to change the generation of href by the uiSref directive, based on the current domain AND the custom domain property.

Active route should be determined as either "mainhome" or "bloghome" depending on the current domain.

When visiting http://example.com/:

<a uiSref="mainhome"> becomes <a href="/">

<a uiSref="bloghome"> becomes <a href="http://me.example.com/">

When visiting http://me.example.com/:

<a uiSref="mainhome"> becomes <a href="http://example.com/">

<a uiSref="bloghome"> becomes <a href="/">

I'd really appreciate any help regarding this!

1 Answers

Answers 1

ui-router is built to manipulate the path part of the URL not the hostname so your best option is probably to build 2 separate apps.

But you can still do something like what you suggested by providing different routes using window.location.hostname

let states: Ng2StateDeclaration[]; const hostName: string = window.location.hostname; if (hostName.startsWith('example.com')) {     states = [         { name: 'mainhome', url: '/', component: 'MainSiteComponent' }     ]; } else {     states = [         { name: 'bloghome', url: '/', component: 'BlogComponent' }     ]; } 

and in the component you should do:

@Component({     selector: 'my-app',     template: `         <a *ngIf="isMain" uiSref="mainhome" uiSrefActive="active">Main</a>         <a *ngIf="isMain" (click)="switchSite()>Blog</a>         <a *ngIf="!isMain" (click)="switchSite()>Main</a>         <a *ngIf="!isMain" uiSref="bloghome" uiSrefActive="active">Blog</a>         <ui-view></ui-view>     `     }) export class App {     const hostName: string = window.location.hostname;     const isMain = hostName.startsWith('example.com') ? true : false;      public switchSite() {         if (isMain) {             window.location ='me.example.com'         } else {             window.location ='example.com'         }     } } 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment