Skip to content

Instantly share code, notes, and snippets.

@adamduren
Created February 22, 2019 20:19
Show Gist options
  • Save adamduren/3f8e4fe5259cd7c009656497f5329b94 to your computer and use it in GitHub Desktop.
Save adamduren/3f8e4fe5259cd7c009656497f5329b94 to your computer and use it in GitHub Desktop.
Workaround for relative urls with ion-back-button[defaultHref]
<ion-back-button [defaultHref]="relativeUrl('..')"></ion-back-button>
@RelativeLocation()
@Component({
selector: 'page-my-page',
templateUrl: 'my-page.page.html',
styleUrls: ['my-page.page.scss'],
})
export class MyPagePage implements RelativeLocation {
// Needed because TS can't infer the decorator adding the method
public relativeUrl: (relativeUrl: string) => string;
}
// tslint:disable-next-line:interface-name
export interface RelativeLocation {
relativeUrl: (relativeUrl: string) => string;
}
export function RelativeLocation() {
return (target: any) => {
let previousCurrentUrl: string | null;
let cachedNextUrl: string | null;
target.prototype.relativeUrl = (relativeUrl: string = '') => {
const currentUrlString = window.location.toString();
if (previousCurrentUrl === currentUrlString) {
return cachedNextUrl;
}
const nextUrlRelativeString =
window.location.protocol +
'//' +
window.location.host +
window.location.pathname +
'/' +
relativeUrl;
const nextUrl = new URL(nextUrlRelativeString);
previousCurrentUrl = currentUrlString;
cachedNextUrl = nextUrl.pathname.replace(/\/$/, '');
return cachedNextUrl;
};
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment