How can I navigate to pages dynamically?

Hello, I am a beginner of Ionic2.

I have a page that contains a list. When I click one item of the list, it would navigate to another page.

My questions are:

  1. Before I am able to use these pages, I have to import the page first, haven’t I? For these information of pages is from database, is there a technique that I could import these pages dynamically?

  2. When I click one item of the list, I would call the same method ‘this.nav.push(Page)’, how could I pass the Page a specific class instead of a fixed class?

Hi Reikami, did you find the solutions?

Interesting question. Though not sure about in what scenario such a thing would be useful. But still would love to know the answer, if anybody knows it.

@footsure You need the page reference (class) to be able to navigate. If you retrieve the page identificator from the database (like a string or number), you need to be able to convert it to a page reference.

To be able to do that, you can, for instance, create an utilitarian class that receive the identificator and returns the page reference. This utilitarian class would need to import the pages, though. It would be something like:

export class MyUtil {

	public static getPageReference(pageId: number): any {
		switch(pageId) {
			case 1: return MyPage01;
			case 2: return MyPage02;
			case 3: return MyPage03;
			case 4: return MyPage04;
			default: MyPageNotFound;
		}
	}

}

And then convert the page id to get the reference to the page and use it when you need:

onClick(pageId: number) {
	let page = MyUtil.getPageReference(pageId);
	this.navCtrl.push(page);
}

I don’t think that keeping the page identificator in the database is a good approach though…

1 Like

@lucasbasquerotto Thanks bro. As of now, your answer is the best one that I can find. Actually, I never keep any identifier in the DB, that is Reikami’s scenario. :slight_smile: