# Navigation The **\** component is the root view container for navigation. It typically functions as the root container of a page and includes a title bar, content area, and toolbar. The content area switches between the home page content (child components of **\**) and non-home page content (child components of [\](ts-basic-components-navdestination.md)) through routing. > **NOTE** > > This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > > Since API version 11, this component supports the safe area attribute by default, with the default attribute value being **expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM]))**. You can override this attribute to change the default behavior. In earlier versions, you need to use the [expandSafeArea](ts-universal-attributes-expand-safe-area.md) attribute to implement the safe area feature. ## Child Components Supported Since API version 9, it is recommended that this component be used together with the **[\](ts-basic-components-navrouter.md)** component. Since API version 10, it is recommended that this component be used together with the **[\](#navpathstack10)** component and **navDestination** attribute. ## APIs ### Navigation Navigation() ### Navigation10+ Navigation(pathInfos: NavPathStack) Binds a navigation stack to the **\** component. **Parameters** | Name | Type | Mandatory | Description | | --------- | ------------------------------- | ---- | ------ | | pathInfos | [NavPathStack](#navpathstack10) | No | Information about the navigation stack.| ## Attributes In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. | Name | Type | Description | | ---------------------------------- | ---------------------------------------- | ---------------------------------------- | | title | [ResourceStr](ts-types.md#resourcestr)10+ \| [CustomBuilder](ts-types.md#custombuilder8)\| [NavigationCommonTitle](#navigationcommontitle)9+ \| [NavigationCustomTitle](#navigationcustomtitle)9+ | Page title.
**NOTE**
When the NavigationCustomTitle type is used to set the height, the **titleMode** attribute does not take effect.
When the title string is too long: (1) If no subtitle is set, the string is scaled down, wrapped in two lines, and then clipped with an ellipsis (...); (2) If a subtitle is set, the subtitle is scaled down and then clipped with an ellipsis (...).| | subTitle(deprecated) | string | Subtitle of the page. If this attribute is not set, no subtitle is displayed. This attribute is deprecated since API version 9. You are advised to use **title** instead.| | menus | Array<[NavigationMenuItem](#navigationmenuitem)> \| [CustomBuilder](ts-types.md#custombuilder8) | Menu items in the upper right corner of the page. If this attribute is not set, no menu item is displayed. When the value type is Array<[NavigationMenuItem](#navigationmenuitem)>, the menu shows a maximum of three icons in portrait mode and a maximum of five icons in landscape mode, with excess icons (if any) placed under the automatically generated **More** icon.| | titleMode | [NavigationTitleMode](#navigationtitlemode) | Display mode of the page title bar.
Default value: **NavigationTitleMode.Free**| | toolBar(deprecated) | [object](#object) \| [CustomBuilder](ts-types.md#custombuilder8) | Content of the toolbar. If this attribute is not set, no toolbar is displayed.
**items**: all items on the toolbar.
**NOTE**
Items are evenly distributed on the toolbar at the bottom. Text and icons are evenly distributed in each content area. If the text is too long, it is scaled down level by level, wrapped in two lines, and then clipped with an ellipsis (...).
This API is deprecated since API version 10. You are advised to use **toolbarConfiguration** instead.| | toolbarConfiguration10+ | Array<[ToolbarItem](#toolbaritem10)> \| [CustomBuilder](ts-types.md#custombuilder8) | Content of the toolbar. If this attribute is not set, no toolbar is displayed.
**NOTE**
When the value type is Array<[ToolbarItem](#ToolbarItem>, the toolbar exhibits the following features:
Items are evenly distributed on the toolbar at the bottom. Text and icons are evenly distributed in each content area.
If any item contains overlong text and there are fewer than five items, the following measures are taken: 1. Increase the item's width to accommodate the text until it is as large as the screen width; 2. Scale down the text level by level; 3. Wrap the text in two lines; 4. Clip the text with an ellipsis (...).
The toolbar shows a maximum of five icons in portrait mode, with excess icons (if any) placed under the automatically generated **More** icon. In landscape mode, this attribute must be used together with Array<[NavigationMenuItem](#navigationmenuitem)> of the **menus** attribute; the toolbar at the bottom is automatically hidden, and all items on the toolbar are moved to the menu in the upper right corner of the screen.
When the value type is [CustomBuilder](ts-types.md#custombuilder8), and the toolbar does not exhibit the preceding features except that items are evenly distributed on the toolbar at the bottom.| | hideToolBar | boolean | Whether to hide the toolbar.
Default value: **false**
**true**: Hide the toolbar.
**false**: Show the toolbar.| | hideTitleBar | boolean | Whether to hide the title bar.
Default value: **false**
**true**: Hide the title bar.
**false**: Show the title bar.| | hideBackButton | boolean | Whether to hide the back button.
Default value: **false**
**true**: Hide the back button.
**false**: Show the back button.
The back button in the title bar of the **\** component cannot be hidden.
**NOTE**
The back button works only when **titleMode** is set to **NavigationTitleMode.Mini**.| | navBarWidth9+ | [Length](ts-types.md#length) | Width of the navigation bar.
Default value: **240**
Unit: vp
**NOTE**
This attribute is valid only when the **\** component is split.| | navBarPosition9+ | [NavBarPosition](#navbarposition) | Position of the navigation bar.
Default value: **NavBarPosition.Start**
**NOTE**
This attribute is valid only when the **\** component is split.| | mode9+ | [NavigationMode](#navigationmode) | Display mode of the navigation bar.
Default value: **NavigationMode.Auto**
At the default settings, the component adapts to a single column or two columns based on the component width.
**NOTE**
Available options are **Stack**, **Split**, and **Auto**.| | backButtonIcon9+ | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Back button icon on the navigation bar. The back button in the title bar of the **\** component cannot be hidden.| | hideNavBar9+ | boolean | Whether to hide the navigation bar. If this parameter is set to **true**, the navigation bar, including the title bar, content area, and toolbar, is hidden. In this case, if the navigation destination page is in the navigation stack, it is moved to the top of the stack and displayed. Otherwise, a blank page is displayed. From API version 9 to API version 10, this attribute takes effect only in dual-column mode. Since API version 11, this attribute takes effect in single-column, dual-column, and auto modes.
Default value: **false**| | navDestination10+ | builder: (name: string, param: unknown) => void | Builder for a **\** component.
**NOTE**
The **builder** function is used, with the **name** and **param** parameters passed in. In the builder, a layer of custom components can be included outside the **\** component. However, no attributes or events can be set for the custom components. Otherwise, only blank components are displayed.| | navBarWidthRange10+ | [[Dimension](ts-types.md#dimension10), [Dimension](ts-types.md#dimension10)] | Minimum and maximum widths of the navigation bar (valid in dual-column mode).
Default value: **240** for the minimum value; 40% of the component width (not greater than 432) for the maximum value
Unit: vp
Priority rules:
Custom value > Default value
Minimum value > Maximum value
navBar > content
If custom values conflict, the global value takes precedence, and the local minimum value depends on the container size.| | minContentWidth10+ | [Dimension](ts-types.md#dimension10) | Minimum width of the navigation bar content area (valid in dual-column mode).
Default value: **360**
Unit: vp
Priority rules:
Custom value > Default value
Minimum value > Maximum value
navBar > content
If custom values conflict, the global value takes precedence, and the local minimum value depends on the container size.
Breakpoint calculation in Auto mode: default 600 vp = minNavBarWidth (240 vp) + minContentWidth (360 vp)| ## Events | Name | Description | | ---------------------------------------- | ---------------------------------------- | | onTitleModeChange(callback: (titleMode: NavigationTitleMode) => void) | Called when **titleMode** is set to **NavigationTitleMode.Free** and the title bar mode changes as content scrolls.| | onNavBarStateChange(callback: (isVisible: boolean) => void) | Called when the navigation bar visibility status changes. The value **true** means that the navigation bar is displayed, and **false** means the opposite.| | onNavigationModeChange(callback: (mode: NavigationMode) => void) 11+| Called when the **\** component is displayed for the first time or its display mode switches between single-column and dual-column.
**NavigationMode.Split**: The component is displayed in two columns.
**NavigationMode.Stack**: The component is displayed in a single column.| | customNavContentTransition(delegate(from: [NavContentInfo](#navcontentinfo11), to: [NavContentInfo](#navcontentinfo11), operation: [NavigationOperation](#navigationoperation11)): [NavigationAnimatedTransition](#navigationanimatedtransition11)11+ | Callback of the custom transition animation.
**from**: parameters of the exit destination page.
**to**: parameters of the enter destination page.
**operation**: transition type.| ## NavPathStack10+ Implements a navigation stack. ### pushPath10+ pushPath(info: NavPathInfo, animated?: boolean): void Pushes the navigation destination page specified by **info** to the navigation stack. **Parameters** | Name | Type | Mandatory | Description | | ---- | ----------------------------- | ---- | -------------------- | | info | [NavPathInfo](#navpathinfo10) | Yes | Information about the navigation destination page.| | animated11+ | boolean | No | Whether to support transition animation.
Default value: **true**| ### pushPathByName10+ pushPathByName(name: string, param: unknown, animated?: boolean): void Pushes the navigation destination page specified by **name**, with the data specified by **param**, to the navigation stack. **Parameters** | Name | Type | Mandatory | Description | | ----- | ------- | ---- | --------------------- | | name | string | Yes | Name of the navigation destination page. | | param | unknown | Yes | Detailed parameters of the navigation destination page.| | animated11+ | boolean | No | Whether to support transition animation.
Default value: **true**| ### replacePath11+ replacePath(info: NavPathInfo, animated?: boolean): void Replaces the top of the navigation stack with the page specified by **info**. **Parameters** | Name | Type | Mandatory | Description | | ---- | ----------------------------- | ---- | -------------------- | | info | [NavPathInfo](#navpathinfo10) | Yes | Parameters of the page to replace the top of the navigation stack.| | animated11+ | boolean | No | Whether to support transition animation.
Default value: **true**| ### replacePathByName11+ replacePathByName(name: string, param: Object, animated?: boolean): void Replaces the top of the navigation stack with the page specified by **name**. **Parameters** | Name | Type | Mandatory | Description | | ----- | ------- | ---- | --------------------- | | name | string | Yes | Name of the navigation destination page. | | param | Object | Yes | Detailed parameters of the navigation destination page.| | animated11+ | boolean | No | Whether to support transition animation.
Default value: **true**| ### removeByIndexes11+ removeByIndexes(indexes: Array): number Removes the navigation destination pages specified by **indexes** from the navigation stack. **Parameters** | Name | Type | Mandatory | Description | | ----- | ------- | ---- | --------------------- | | indexes | Array | Yes | Array of indexes of the navigation destination pages to remove. | **Return value** | Type | Description | | ----------- | ------------------------ | | number | Number of the navigation destination pages removed.| ### removeByName11+ removeByName(name: string): number Removes the navigation destination page specified by **name** from the navigation stack. **Parameters** | Name | Type | Mandatory | Description | | ----- | ------- | ---- | --------------------- | | name | string | Yes | Name of the navigation destination page to remove. | **Return value** | Type | Description | | ----------- | ------------------------ | | number | Number of the navigation destination pages removed.| ### pop10+ pop(animated?: boolean): NavPathInfo | undefined Pops the top element out of the navigation stack. **Parameters** | Name | Type | Mandatory | Description | | ---- | ----------------------------- | ---- | -------------------- | | animated11+ | boolean | No | Whether to support transition animation.
Default value: **true**| **Return value** | Type | Description | | ----------- | ------------------------ | | NavPathInfo | Returns the information about the navigation destination page at the top of the stack.| | undefined | Returns **undefined** if the navigation stack is empty. | ### popToName10+ popToName(name: string, animated?: boolean): number Returns the navigation stack to the first navigation destination page that matches the value of **name**. **Parameters** | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ------------------- | | name | string | Yes | Name of the navigation destination page.| | animated11+ | boolean | No | Whether to support transition animation.
Default value: **true**| **Return value** | Type | Description | | ------ | ---------------------------------------- | | number | Returns the index of the first navigation destination page that matches the value of **name** if it exists in the navigation stack; returns **-1** otherwise.| ### popToIndex10+ popToIndex(index: number, animated?: boolean): void Returns the navigation stack to the page specified by **index**. **Parameters** | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ---------------------- | | index | number | Yes | Index of the navigation destination page.| | animated11+ | boolean | No | Whether to support transition animation.
Default value: **true**| ### moveToTop10+ moveToTop(name: string, animated?: boolean): number Moves to the top of the navigation stack the first navigation destination page that matches the value of **name**. **Parameters** | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ------------------- | | name | string | Yes | Name of the navigation destination page.| | animated11+ | boolean | No | Whether to support transition animation.
Default value: **true**| **Return value** | Type | Description | | ------ | ---------------------------------------- | | number | Returns the index of the first navigation destination page that matches the value of **name** if it exists in the navigation stack; returns **-1** otherwise.| ### moveIndexToTop10+ moveIndexToTop(index: number, animated?: boolean): void Moves to the top of the navigation stack the navigation destination page that matches the value of **index**. **Parameters** | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ---------------------- | | index | number | Yes | Index of the navigation destination page.| | animated11+ | boolean | No | Whether to support transition animation.
Default value: **true**| ### clear10+ clear(animated?: boolean): void Clears the navigation stack. **Parameters** | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ---------------------- | | animated11+ | boolean | No | Whether to support transition animation.
Default value: **true**| ### getAllPathName10+ getAllPathName(): Array Obtains the names of all navigation destination pages in the navigation stack. **Return value** | Type | Description | | -------------- | -------------------------- | | Array | Names of all navigation destination pages in the navigation stack.| ### getParamByIndex10+ getParamByIndex(index: number): unknown | undefined Obtains the parameter information of the navigation destination page that matches the value of **index**. **Parameters** | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ---------------------- | | index | number | Yes | Index of the navigation destination page.| **Return value** | Type | Description | | --------- | -------------------------- | | unknown | Returns the parameter information of the matching navigation destination page.| | undefined | Returns **undefined** if the passed index is invalid. | ### getParamByName10+ getParamByName(name: string): Array Obtains the parameter information of all the navigation destination pages that match the value of **name**. **Parameters** | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ------------------- | | name | string | Yes | Name of the navigation destination page.| **Return value** | Type | Description | | --------------- | --------------------------------- | | Array | Parameter information of all the matching navigation destination pages.| ### getIndexByName10+ getIndexByName(name: string): Array Obtains the indexes of all the navigation destination pages that match the value of **name**. **Parameters** | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ------------------- | | name | string | Yes | Name of the navigation destination page.| **Return value** | Type | Description | | -------------- | --------------------------------- | | Array | Indexes of all the matching navigation destination pages.| ### size10+ size(): number Obtains the stack size. **Return value** | Type | Description | | ------ | ------ | | number | Stack size.| ### disableAnimation11+ disableAnimation(value: boolean): void Disables or enables the transition animation in the **\** component. **Parameters** | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ---------------------- | | value | boolean | No | Whether to disable the transition animation.
Default value: **false**| ## NavPathInfo10+ Provides the navigation page information. ### constructor constructor(name: string, param: unknown) **Parameters** | Name | Type | Mandatory | Description | | ----- | ------- | ---- | --------------------- | | name | string | Yes | Name of the navigation destination page. | | param | unknown | No | Detailed parameters of the navigation destination page.| ## NavContentInfo11+ Provides the destination information. **Parameters** | Name | Type | Mandatory | Description | |-------|-------|------|-------| | name | string | No| Name of the navigation destination. If the view is a root view (**NavBar**), the return value is **undefined**.| | index | number | Yes| Index of the navigation destination in the navigation stack. If the view is a root view (**NavBar**), the return value is **-1**.| | mode | [NavDestinationMode](ts-basic-components-navdestination.md#navdestinationmode11) | No| Mode of the navigation destination. If the view is a root view (**NavBar**), the return value is **undefined**.| ## NavigationAnimatedTransition11+ Defines the custom transition animation protocol. You need to implement this protocol to define the redirection animation of the navigation route. **Parameters** | Name| Type| Mandatory| Description| |------|-----|-----|------| | timeout | number | No| Animation timeout time.
Unit: ms
Default value: **1000**| | transition | (transitionProxy : [NavigationTransitionProxy](#navigationtransitionproxy-11)): void | Yes| Callback for executing the custom transition animation.
**transitionProxy**: proxy for the custom transition animation.| | onTransitionEnd | (success: boolean):void | No| Callback invoked when the transition is complete.
**success**: whether the transition is successful.| ## NavigationTransitionProxy 11+ Implements a custom transition animation proxy. **Parameters** | Name| Type | Mandatory| Description | |------|-------|-----|-------| | from | [NavContentInfo](#navcontentinfo11) | Yes| Information about the exit page.| | to | [NavContentInfo](#navcontentinfo11) | Yes| Information about the enter page.| ### finishTransition Finishes this custom transition animation. This API must be manually called to end the animation. Otherwise, the system ends the animation when the timeout expires. ## NavigationMenuItem | Name | Type | Mandatory | Description | | ------ | ------------- | ---- | --------------- | | value | string | Yes | Text of the menu item. Its visibility varies by the API version.
API version 9: visible.
API version 10: invisible. | | icon | string | No | Icon path of the menu item.| | action | () => void | No | Callback invoked when the menu item is selected. | ## object | Name | Type | Mandatory | Description | | ------ | ------------- | ---- | --------------- | | value | string | Yes | Text of a toolbar item. | | icon | string | No | Icon path of a toolbar item.| | action | () => void | No | Callback invoked when a toolbar item is selected. | ## ToolbarItem10+ | Name | Type | Mandatory | Description | | ---------- | ---------------------------------------- | ---- | ---------------------------------------- | | value | ResourceStr | Yes | Text of a toolbar item. | | icon | ResourceStr | No | Icon path of a toolbar item. | | action | () => void | No | Callback invoked when a toolbar item is selected. | | status | [ToolbarItemStatus](#toolbaritemstatus10) | No | Status of a toolbar item.
Default value: **ToolbarItemStatus.NORMAL**| | activeIcon | ResourceStr | No | Icon path of the toolbar item in the active state. | ## ToolbarItemStatus10+ | Name | Description | | -------- | ---------------------------------------- | | NORMAL | Normal state. In this state, the toolbar item takes on the default style and can switch to another state-specific style by responding to the hover, press, and focus events.| | DISABLED | Disabled state. In this state, the toolbar item is disabled and does not allow for user interactions.| | ACTIVE | Active state. In this state, the toolbar item can update its icon to the one specified by **activeIcon** by responding to a click event.| ## NavigationTitleMode | Name | Description | | ---- | ---------------------------------------- | | Free | When the content is a scrollable component, the main title shrinks as the content scrolls down (the subtitle fades out with its size remaining unchanged) and restores as the content scrolls up to the top.
**NOTE**
The size linkage effect works only when **title** is set to **ResourceStr** or **NavigationCommonTitle**. If **title** is set to any other value type, the main title changes in mere location when pulled down.| | Mini | The title is fixed at mini mode. | | Full | The title is fixed at full mode. | ## NavigationCommonTitle | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ------ | | main | string | Yes | Main title.| | sub | string | Yes | Subtitle.| ## NavigationCustomTitle | Name | Type | Mandatory | Description | | ------- | ---------------------------------------- | ---- | -------- | | builder | [CustomBuilder](ts-types.md#custombuilder8) | Yes | Content of the title bar.| | height | [TitleHeight](#titleheight) \| [Length](ts-types.md#length) | Yes | Height of the title bar.| ## NavBarPosition | Name | Description | | ----- | ---------------- | | Start | When two columns are displayed, the main column is at the start of the main axis.| | End | When two columns are displayed, the main column is at the end of the main axis.| ## NavigationMode | Name | Description | | ----- | ------------------------------------------------------------ | | Stack | The navigation bar and content area are displayed independently of each other, which are equivalent to two pages. | | Split | The navigation bar and content area are displayed in different columns.
The values of **navBarWidthRange** are represented by [minNavBarWidth,maxNavBarWidth].
1. When the value of **navBarWidth** is beyond the value range specified by **navBarWidthRange**, **navBarWidth** is set according to the following rules:
Value of **navBarWidth** < Value of **minNavBarWidth**: The value of **navBarWidth** is changed to that of **minNavBarWidth**.
Value of **navBarWidth** > Value of **maxNavBarWidth** and Result of [Component width - Value of **minContentWidth** - Divider width (1 vp)] > Value of **maxNavBarWidth**: The value of **navBarWidth** is changed to that of **maxNavBarWidth**.
Value of **navBarWidth** > Value of **maxNavBarWidth** and Result of [Component width - Value of **minContentWidth** - Divider width (1 vp)] < Value of **maxNavBarWidth**: The value of **navBarWidth** is changed to that of **minNavBarWidth**.
Value of **navBarWidth** > Value of **maxNavBarWidth** and Component width - Value of **minContentWidth** - Divider width (1 vp) is within the value range specified by **navBarWidthRange**: The value of **navBarWidth** is changed to Component width - Value of **minContentWidth** - Divider width (1 vp).
2. When the value of **navBarWidth** is within the value range specified by **navBarWidthRange**, **navBarWidth** is set according to the following rules:
Value of **minNavBarWidth** + Value of **minContentWidth** + Divider width (1 vp) > = Component width: The value of **navBarWidth** is changed to that of **minNavBarWidth**.
Value of **minNavBarWidth** + Value of **minContentWidth** + Divider width (1 vp) < Component width and Value of **navBarWidth** + Value of **minContentWidth** + Divider width (1 vp) > = Component width: The value of **navBarWidth** is changed to Component width - Value of **minContentWidth** - Divider width (1 vp).
Value of **minNavBarWidth** + Value of **minContentWidth** + Divider width (1 vp) < Component width and Value of **navBarWidth** + Value of **minContentWidth** + Divider width (1 vp) < Component width: The value of **navBarWidth** is the set value.
3. When the component size is decreased, the content area is shrunk until its width reaches the value defined by **minContentWidth**, and then the navigation bar is shrunk until its width reaches the value defined by **minNavBarWidth**; if the component size is further decreased, the content area is further shrunk until it disappears, and then navigation bar is shrunk.
4. When the navigation bar is set to a fixed size and the component size is continuously decreased, the navigation bar is shrunk.
5. If only **navBarWidth** is set, the width of the navigation bar is fixed at the value of **navBarWidth**, and the divider cannot be dragged.| | Auto | In API version 9 and earlier versions: If the window width is greater than or equal to 520 vp, the Split mode is used; otherwise, the Stack mode is used.
In API version 10 and later versions: If the window width is greater than or equal to 600 vp, the Split mode is used; otherwise, the Stack mode is used. 600 vp = minNavBarWidth (240 vp) + minContentWidth (360 vp).| ## TitleHeight | Name | Description | | ----------- | -------------------------- | | MainOnly | Recommended height (56 vp) of the title bar when only the main title is available. | | MainWithSub | Recommended height (82 vp) of the title bar when both the main title and subtitle exist.| ## NavigationOperation11+ | Name | Description | |---------|------| |PUSH | The transition is enter transition.| |POP | The transition is exit transition.| | REPLACE | The transition is page replacement.| > **NOTE** > > Among the scrollable components, only **\** is supported. ## Example ### Example 1 ```ts // xxx.ets class A { text: string = '' num: number = 0 } @Entry @Component struct NavigationExample { private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] @State currentIndex: number = 0 @Builder NavigationTitle() { Column() { Text('Title') .fontColor('#182431') .fontSize(30) .lineHeight(41) .fontWeight(700) Text('subtitle') .fontColor('#182431') .fontSize(14) .lineHeight(19) .opacity(0.4) .margin({ top: 2, bottom: 20 }) }.alignItems(HorizontalAlign.Start) } @Builder NavigationMenus() { Row() { Image('resources/base/media/ic_public_add.svg') .width(24) .height(24) Image('resources/base/media/ic_public_add.svg') .width(24) .height(24) .margin({ left: 24 }) Image('common/ic_public_more.svg') .width(24) .height(24) .margin({ left: 24 }) } } build() { Column() { Navigation() { TextInput({ placeholder: 'search...' }) .width('90%') .height(40) .backgroundColor('#FFFFFF') .margin({ top: 8 }) List({ space: 12, initialIndex: 0 }) { ForEach(this.arr, (item: number) => { ListItem() { Text('' + item) .width('90%') .height(72) .backgroundColor('#FFFFFF') .borderRadius(24) .fontSize(16) .fontWeight(500) .textAlign(TextAlign.Center) } }, (item: number) => item.toString()) } .height(324) .width('100%') .margin({ top: 12, left: '10%' }) } .title(this.NavigationTitle) .menus(this.NavigationMenus) .titleMode(NavigationTitleMode.Full) .toolbarConfiguration([ { value: $r("app.string.navigation_toolbar_add"), icon: $r("app.media.ic_public_highlightsed") }, { value: $r("app.string.navigation_toolbar_app"), icon: $r("app.media.ic_public_highlights") }, { value: $r("app.string.navigation_toolbar_collect"), icon: $r("app.media.ic_public_highlights") } ]) .hideTitleBar(false) .hideToolBar(false) .onTitleModeChange((titleModel: NavigationTitleMode) => { console.info('titleMode' + titleModel) }) }.width('100%').height('100%').backgroundColor('#F1F3F5') } } ``` ![en-us_image_navigation](figures/en-us_image_navigation.png) ### Example 2 ```ts // Index.ets import { PageOneTmp } from './PageOne' import { pageTwoTmp } from './PageTwo' import { Pages } from './PageTwo' @Entry @Component struct NavigationExample { @Provide('pageInfos') pageInfos: NavPathStack = new NavPathStack() @Builder PageMap(name: string) { if (name === 'pageOne') { PageOneTmp() } else if (name === 'pageTwo') { pageTwoTmp({ names: name, values: this.pageInfos } as Pages) } } build() { Navigation(this.pageInfos) { Column() { Button('pushPath', { stateEffect: true, type: ButtonType.Capsule }) .width('80%') .height(40) .margin(20) .onClick(() => { this.pageInfos.pushPath({ name:'pageOne'}) // Push the navigation destination page specified by name to the navigation stack. }) } }.title('NavIndex').navDestination(this.PageMap) } } ``` ```ts // PageOne.ets class TmpClass{ count:number=10 } @Component export struct PageOneTmp { @Consume('pageInfos') pageInfos: NavPathStack; build() { NavDestination() { Column() { Button('pushPathByName', { stateEffect: true, type: ButtonType.Capsule }) .width('80%') .height(40) .margin(20) .onClick(() => { let tmp = new TmpClass() this.pageInfos.pushPathByName('pageTwo', tmp) // Push the navigation destination page specified by name to the navigation stack, with the data specified by param passed in. }) Button('popToname', { stateEffect: true, type: ButtonType.Capsule }) .width('80%') .height(40) .margin(20) .onClick(() => { this.pageInfos.popToName('pageTwo') // Return the navigation stack to the first navigation destination page that matches the value of name. console.log('popToName' + JSON.stringify(this.pageInfos), 'Return value' + JSON.stringify(this.pageInfos.popToName('pageTwo'))) }) Button('popToIndex', { stateEffect: true, type: ButtonType.Capsule }) .width('80%') .height(40) .margin(20) .onClick(() => { this.pageInfos.popToIndex(1) // Return the navigation stack to the navigation destination page that matches the value of index. console.log('popToIndex' + JSON.stringify(this.pageInfos)) }) Button('moveToTop', { stateEffect: true, type: ButtonType.Capsule }) .width('80%') .height(40) .margin(20) .onClick(() => { this.pageInfos.moveToTop('pageTwo') // Move to the top of the navigation stack the first navigation destination page that matches the value of name. console.log('moveToTop' + JSON.stringify(this.pageInfos), 'Return value' + JSON.stringify(this.pageInfos.moveToTop('pageTwo'))) }) Button('moveIndexToTop', { stateEffect: true, type: ButtonType.Capsule }) .width('80%') .height(40) .margin(20) .onClick(() => { this.pageInfos.moveIndexToTop(1) // Move to the top of the navigation stack the navigation destination page that matches the value of index. console.log('moveIndexToTop' + JSON.stringify(this.pageInfos)) }) Button('clear', { stateEffect: true, type: ButtonType.Capsule }) .width('80%') .height(40) .margin(20) .onClick(() => { this.pageInfos.clear() // Clear the navigation stack. }) Button('get', { stateEffect: true, type: ButtonType.Capsule }) .width('80%') .height(40) .margin(20) .onClick(() => { console.log('-------------------') console.log('Obtained the names of all pages in the navigation stack', JSON.stringify(this.pageInfos.getAllPathName())) console.log('Obtained parameter information of the navigation destination page specified by index', JSON.stringify(this.pageInfos.getParamByIndex(1))) console.log('Obtained parameter information of all the navigation destination pages specified by name', JSON.stringify(this.pageInfos.getParamByName('pageTwo'))) console.log('Obtained the index information of all the navigation destination pages specified by name', JSON.stringify(this.pageInfos.getIndexByName('pageOne')))) console.log ('Obtained the stack size', JSON.stringify (this.pageInfos.size ())) }) }.width('100%').height('100%') }.title('pageOne') .onBackPressed(() => { const popDestinationInfo = this.pageInfos.pop() // Pops the top element out of the navigation stack. console.log('pop' + 'Return value' + JSON.stringify(popDestinationInfo)) return true }) } } ``` ```ts // PageTwo.ets export class Pages { names: string = "" values: NavPathStack | null = null } @Builder export function pageTwoTmp(info: Pages) { NavDestination() { Column() { Button('pushPathByName', { stateEffect: true, type: ButtonType.Capsule }) .width('80%') .height(40) .margin(20) .onClick(() => { (info.values as NavPathStack).pushPathByName('pageOne', null) }) }.width('100%').height('100%') }.title('pageTwo') .onBackPressed(() => { (info.values as NavPathStack).pop() return true }) } ``` ![navigation.gif](figures/navigation.gif) ### Example 3 ```ts // Index.ets import { CustomTransition, AnimateCallback } from './CustomNavigationUtils' import { pageOneTmp } from './PageOne' import {PageTwoTemp} from './PageTwo' @Entry @Component struct NavigationExample { @Provide('pageInfos') pageInfos: NavPathStack = new NavPathStack() @Builder PageMap(name: string) { if (name === 'pageOne') { pageOneTmp() } else if (name === 'pageTwo') { PageTwoTemp() } } aboutToAppear() { if (this.pageInfos === undefined) { this.pageInfos = new NavPathStack(); } this.pageInfos.pushPath({name: 'pageOne'}, false) } build() { Navigation(this.pageInfos) { }.title('NavIndex').navDestination(this.PageMap) .hideNavBar(true) .customNavContentTransition((from: NavContentInfo, to: NavContentInfo, operation: NavigationOperation) => { if (from.mode == NavDestinationMode.DIALOG || to.mode == NavDestinationMode.DIALOG) { return undefined; } console.log(`current info: ${to.name}, index: ${to.index}, mode: ${to.mode}`); console.log(`pre info: ${from.name}, index: ${from.index}, mode: ${from.mode}`); console.log(`operation: ${operation}`) if (from.index === -1 || to.index === -1) { return undefined; } let customAnimation: NavigationAnimatedTransition = { onTransitionEnd: (isSuccess: boolean)=>{ console.log(`current transition result is ${isSuccess}`); }, timeout: 700, transition: (transitionProxy: NavigationTransitionProxy)=>{ console.log("trigger transition callback"); let fromParam: AnimateCallback = CustomTransition.getInstance().getAnimateParam(from.name); let toParam: AnimateCallback = CustomTransition.getInstance().getAnimateParam(to.name); fromParam.start(operation == NavigationOperation.PUSH, true); toParam.start(operation == NavigationOperation.PUSH, false); animateTo({duration: 400, onFinish: ()=>{ fromParam.onFinish(operation === NavigationOperation.PUSH, true); toParam.onFinish(operation === NavigationOperation.PUSH, true); transitionProxy.finishTransition(); }}, ()=>{ fromParam.finish(operation === NavigationOperation.PUSH, true) toParam.finish(operation === NavigationOperation.PUSH, false); }) } }; return customAnimation; }) } } ``` ```ts // PageOne.ets import {CustomTransition} from './CustomNavigationUtils' @Component export struct pageOneTmp { @Consume('pageInfos') pageInfos: NavPathStack @State x: number = 0 @State scaleVal: number = 1 aboutToAppear() { CustomTransition.getInstance().registerNavParam('pageOne', (isPush: boolean, isExit: boolean) => { this.x = isExit ? 0 : 300; }, (isPush: boolean, isExit: boolean)=> { this.x = isExit ? -300 : 0; }, (isPush: boolean, isExit: boolean) => { this.x = 0; }, 200); } build() { NavDestination() { Column() { Button('pushPathByName', { stateEffect: true, type: ButtonType.Capsule }) .width('80%') .height(40) .margin(20) .onClick(() => { this.pageInfos.pushPathByName('pageTwo', null) // Push the navigation destination page specified by name to the navigation stack, with the data specified by param passed in. }) }.width('100%').height('100%') }.title('pageOne') .mode(NavDestinationMode.STANDARD) .onBackPressed(() => { const popDestinationInfo = this.pageInfos.pop() // Pops the top element out of the navigation stack. console.log('pop' + 'Return value' + JSON.stringify(popDestinationInfo)) return true }) .onDisAppear(()=>{ let names = this.pageInfos.getAllPathName(); if (names.includes('pageOne')) { return; } CustomTransition.getInstance().unRegisterNavParam('pageOne') }) .translate({x: this.x, y: 0, z: 0}) .backgroundColor(Color.White) } } ``` ```ts // PageTwo.ets import {CustomTransition} from './CustomNavigationUtils' @Component export struct PageTwoTemp { @Consume('pageInfos') pageInfos: NavPathStack @State x: number = 300 aboutToAppear() { CustomTransition.getInstance().registerNavParam('pageTwo', (isPush: boolean, isExit: boolean)=>{ console.log("current page is pageOne") this.x = isExit ? 0 : 300; }, (isPush: boolean, isExit: boolean)=>{ this.x = isExit ? -300 : 0; }, (isPush: boolean, isExit: boolean) => { this.x = 0; }, 200) } build() { NavDestination() { Column() { Button('pushPathByName', { stateEffect: true, type: ButtonType.Capsule }) .width('80%') .height(40) .margin(20) .onClick(() => { this.pageInfos.pushPathByName('pageOne', null) // Push the navigation destination page specified by name to the navigation stack, with the data specified by param passed in. }) }.width('100%').height('100%') }.title('pageTwo') .onBackPressed(() => { const popDestinationInfo = this.pageInfos.pop() // Pops the top element out of the navigation stack. console.log('pop' + 'Return value' + JSON.stringify(popDestinationInfo)) return true }) .onDisAppear(()=>{ let names = this.pageInfos.getAllPathName(); if (names.includes('pageTwo')) { return; } CustomTransition.getInstance().unRegisterNavParam('pageTwo') }) .translate({x: this.x}) .backgroundColor(Color.White) } } ``` ```ts // CustomNavigationUtils.ts export interface AnimateCallback { finish: (isPush: boolean, isExit: boolean) => void; start: (isPush: boolean, isExit: boolean) => void; onFinish: (isPush: boolean, isExit: boolean) => void timeout: number; } const customTransitionMap: Map = new Map() export class CustomTransition { private constructor() { } static delegate = new CustomTransition(); static getInstance() { return this.delegate; } registerNavParam(name: string, startCallback: (operation: boolean, isExit: boolean) => void, endCallback:(operation: boolean, isExit: boolean) => void, onFinish: (opeation: boolean, isExit: boolean) => void, timeout: number): void { if (customTransitionMap.has(name)) { let param = customTransitionMap.get(name); param.start = startCallback; param.finish = endCallback; param.timeout = timeout; param.onFinish = onFinish; return; } let params: AnimateCallback = {timeout: timeout, start: startCallback, finish: endCallback, onFinish: onFinish}; customTransitionMap.set(name, params); } unRegisterNavParam(name: string): void { customTransitionMap.delete(name); } getAnimateParam(name: string): AnimateCallback { let result: AnimateCallback = { start: customTransitionMap.get(name).start, finish: customTransitionMap.get(name).finish, timeout: customTransitionMap.get(name).timeout, onFinish: customTransitionMap.get(name).onFinish }; return result; } } ``` ![customNavigation.gif](figures/customNavigation.gif)