Overview
In Ionic Framework, parameters can be passed to pages using the push
function in an ion-nav
component and parameters can be passed to the root page using the rootPage
parameter. The following code shows how this can be done:
// The navigation element const nav = document.querySelector('ion-nav'); class NewPage extends HTMLElement { async connectedCallback() { this.innerHTML = ` <ion-header class='gallery-page' translucent> <ion-toolbar> <ion-buttons slot="start"> <ion-back-button /> </ion-buttons> <ion-title>Root Page</ion-title> </ion-toolbar> </ion-header> <ion-content fullscreen class="ion-padding"> a: ${this.a}, b: ${this.b} <br /> <ion-button>New Page</ion-button> </ion-content> `; const btn = this.querySelector('ion-button'); btn.addEventListener('click', () => { nav.push('new-page', { a: this.a + 1, b: this.b + 1}); }) } } customElements.define('new-page', NewPage); nav.rootParams = { a: 1, b: 2 }; /* <!-- original body --> <body> <ion-nav root='new-page'></ion-nav> </body> */
This fiddle is a working example of the code.
Problem
If an ion-router
element is used to determine what page should be displayed as the root page (instead of the ion-nav
root
attribute), then rootParam
is ignored.
/* <!-- modified body --> <body> <ion-router> <ion-route url='/' component='new-page'></ion-route> </ion-router> <ion-nav></ion-nav> </body> */
This fiddle is an example of the modified code.
Question
Using Ionic with JavaScript (not Angular, React, or Vue), how can variables be properly passed to the root page when ion-router
is used?
Advertisement
Answer
Since my problem was accepted as a bug for the project on Github, the workaround that I originally posted in the question is the solution.
Preferred Workaround
The window
or document
global objects can be used to store variables, which can be accessed by HTMLElement classes.
Alternative Workaround
Variables can be passed to modules using an initializtion function, but importing and calling the initialize
function becomes a precondition. This requires creating and calling initialize
functions in every module containing an HTMLElement which might be the root page.
// Module initialization code example let a; export function initialize(_a) { _a = a; }