Created
February 22, 2019 20:19
-
-
Save adamduren/3f8e4fe5259cd7c009656497f5329b94 to your computer and use it in GitHub Desktop.
Workaround for relative urls with ion-back-button[defaultHref]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<ion-back-button [defaultHref]="relativeUrl('..')"></ion-back-button> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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