Implementing Page Routing and Navigation in HarmonyOS with ArkUI
Navigate to a Details Page
Here is a DetailsPage component that displays an image and allows its width to be adjusted. The page provides a way to navigate back to the home screen.
import { router } from '@ohos.router';
@Entry
@Component
struct DetailsPage {
@State currentImageWidth: number = 150;
build() {
Column() {
// Display the image
Row() {
Image($r('app.media.application_icon'))
.width(this.currentImageWidth)
}
.width('100%')
.height(400)
.justifyContent(FlexAlign.Center)
// Control to manually input the image width
Row() {
Text('Image Width')
.fontSize(20)
.fontWeight(FontWeight.Bold)
TextInput({ text: this.currentImageWidth.toString() })
.width(150)
.backgroundColor(Color.White)
.type(InputType.Number)
.onChange((value: string) => {
this.currentImageWidth = parseInt(value);
})
}
.width('100%')
.padding({ left: 14, right: 14 })
.justifyContent(FlexAlign.SpaceBetween)
Divider().width('91%')
// Buttons to resize the image
Row() {
Button('Reduce Size')
.width(80)
.fontSize(20)
.onClick(() => {
if (this.currentImageWidth >= 10) {
this.currentImageWidth -= 10;
}
})
Button('Increase Size')
.width(80)
.fontSize(20)
.onClick(() => {
if (this.currentImageWidth < 300) {
this.currentImageWidth += 10;
}
})
}
.width('100%')
.margin({ top: 35, bottom: 35 })
.justifyContent(FlexAlign.SpaceEvenly)
// Button to navigate back to the Home page
Button('Return to Home')
.width(160)
.fontSize(20)
.onClick(() => {
router.back();
})
// Slider for adjusting the image width
Slider({
min: 100,
max: 300,
value: this.currentImageWidth,
step: 10,
})
.width('100%')
.trackColor('#36D')
.trackThickness(5)
.showTips(true)
.onChange((value: number) => {
this.currentImageWidth = value;
})
}
.width('100%')
.height('100%')
}
}
Removing the Home Page from the Navigation Stack
When you don't want to keep the current page in the navigation history (e.g., navigating from a Login to a Profile page), use router.replaceUrl. This replaces the current page, so pressing the back button will exit the application.
import { router } from '@ohos.router';
function navigateToProfilePage() {
router.replaceUrl({
url: 'pages/ProfilePage'
}, router.RouterMode.Standard, (err) => {
if (err) {
console.error(`Replace operation failed: ${err.code}, ${err.message}`);
return;
}
console.log('Navigation successful.');
});
}
Keeping the Home Page in the Navigation Stack
To preserve the current page in the navigation stack (e.g., navigating from a Settings page to a Theme selection page and expecting to return), use router.pushUrl with RouterMode.Single.
import { router } from '@ohos.router';
function navigateToThemePage() {
router.pushUrl({
url: 'pages/ThemePage'
}, router.RouterMode.Single, (err) => {
if (err) {
console.error(`Push operation failed: ${err.code}, ${err.message}`);
return;
}
console.log('Navigation successful.');
});
}
To navigate and replace the current page while keeping the underlying stack intact (e.g., from a Search Results list to a Search Detail page), use router.replaceUrl with RouterMode.Single.
import { router } from '@ohos.router';
function navigateToDetailPage() {
router.replaceUrl({
url: 'pages/SearchDetail'
}, router.RouterMode.Single, (err) => {
if (err) {
console.error(`Replace operation failed: ${err.code}, ${err.message}`);
return;
}
console.log('Navigation successful.');
});
}
Passing and Receiving Page Parameters
Sending Parameters to a New Page
You can send complex data as parameters when navigating.
interface UserProfile {
score: number;
}
interface NavigationPayload {
userId: number;
profile: UserProfile;
}
function goToUserPage() {
const payload: NavigationPayload = {
userId: 789,
profile: {
score: 95
}
};
router.pushUrl({
url: 'pages/UserPage',
params: payload
}, (err) => {
if (err) {
console.error(`Push failed: ${err.code}, ${err.message}`);
return;
}
console.log('Navigation with parameters succeeded.');
});
}
Receiving Parameters on the Target Page
Retrieve the past parameters using router.getParams().
const receivedParams = router.getParams();
const userId = receivedParams['userId'];
const userScore = receivedParams['profile'].score;
Sending Parameters When Navigating Back
You can also send data back to the previous page.
router.back({
url: 'pages/HomePage',
params: {
message: 'Data sent from the current page'
}
});
Receiving Parameters on the Returning Page
Access the parameters in the onPageShow lifecycle function.
onPageShow() {
const returnParams = router.getParams();
const message = returnParams['message'];
}
Adding a Confirmation Dialog Before Page Exit
Using the Default System Dialog
The router module can show a default confirmation dialog when trying to navigate away from a page with unsaved changes.
import { router } from '@ohos.router';
@Entry
@Component
struct EditorPage {
build() {
Column() {
// Page content here
}
}
// The system will automatically prompt the user if they try to leave
}
Implementing a Custom Confirmation Dialog
For more control, use @ohos.promptAction to create a custom dialog.
import { router } from '@ohos.router';
import promptAction from '@ohos.promptAction';
function confirmExit() {
promptAction.showDialog({
title: 'Leave Page?',
message: 'Your changes have not been saved. Are you sure you want to leave?',
buttons: [
{ text: 'Stay', color: '#333333' },
{ text: 'Leave', color: '#007AFF' }
]
}).then((result) => {
if (result.index === 0) {
// User chose 'Stay'
console.log('User canceled the navigation.');
} else if (result.index === 1) {
// User chose 'Leave'
console.log('User confirmed navigation.');
router.back();
}
}).catch((err) => {
console.error(`Dialog failed: ${err.code}, ${err.message}`);
});
}