• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Navigation
2
3The **\<Navigation>** 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 **\<Navigation>**) and non-home page content (child components of [\<NavDestination>](ts-basic-components-navdestination.md)) through routing.
4
5> **NOTE**
6>
7> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
8
9
10## Child Components
11
12Supported
13
14Since API version 9, it is recommended that this component be used together with the **[\<NavRouter>](ts-basic-components-navrouter.md)** component.
15
16Since API version 10, it is recommended that this component be used together with the **[\<NavPathStack>](#navpathstack10)** component and **navDestination** attribute.
17
18## APIs
19
20### Navigation
21
22Navigation()
23
24### Navigation<sup>10+</sup>
25
26Navigation(pathInfos: NavPathStack)
27
28Binds a navigation stack to the **\<Navigation>** component.
29
30**Parameters**
31
32| Name      | Type                           | Mandatory  | Description  |
33| --------- | ------------------------------- | ---- | ------ |
34| pathInfos | [NavPathStack](#navpathstack10) | No   | Information about the navigation stack.|
35
36## Attributes
37
38In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
39
40| Name                                | Type                                    | Description                                      |
41| ---------------------------------- | ---------------------------------------- | ---------------------------------------- |
42| title                              | [ResourceStr](ts-types.md#resourcestr)<sup>10+</sup> \| [CustomBuilder](ts-types.md#custombuilder8)<sup>8+</sup> \| [NavigationCommonTitle](#navigationcommontitle9)<sup>9+</sup> \| [NavigationCustomTitle](#navigationcustomtitle9)<sup>9+</sup> | Page title.<br>**NOTE**<br>When the NavigationCustomTitle type is used to set the height, the **titleMode** attribute does not take effect.<br>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 (...).|
43| subTitle<sup>(deprecated)</sup>    | 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.|
44| menus                              | Array<[NavigationMenuItem](#navigationmenuitem)&gt; \| [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)&gt;, 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.|
45| titleMode                          | [NavigationTitleMode](#navigationtitlemode) | Display mode of the page title bar.<br>Default value: **NavigationTitleMode.Free**|
46| toolBar<sup>(deprecated)</sup>     | [object](#object) \| [CustomBuilder](ts-types.md#custombuilder8) | Content of the toolbar. If this attribute is not set, no toolbar is displayed.<br>**items**: all items on the toolbar.<br>**NOTE**<br>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 (...).<br>This API is deprecated since API version 10. You are advised to use **toolbarConfiguration** instead.|
47| toolbarConfiguration<sup>10+</sup> | Array<[ToolbarItem](#toolbaritem10)&gt; \| [CustomBuilder](ts-types.md#custombuilder8) | Content of the toolbar. If this attribute is not set, no toolbar is displayed.<br>**NOTE**<br>When the value type is Array<[ToolbarItem](#ToolbarItem>, the toolbar exhibits the following features:<br>Items are evenly distributed on the toolbar at the bottom. Text and icons are evenly distributed in each content area.<br>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 (...).<br>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.<br>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.|
48| hideToolBar                        | boolean                                  | Whether to hide the toolbar.<br>Default value: **false**<br>**true**: Hide the toolbar.<br>**false**: Show the toolbar.|
49| hideTitleBar                       | boolean                                  | Whether to hide the title bar.<br>Default value: **false**<br>**true**: Hide the title bar.<br>**false**: Show the title bar.|
50| hideBackButton                     | boolean                                  | Whether to hide the back button in the title bar. The back button in the title bar of the **\<NavDestination>** component cannot be hidden.<br>Default value: **false**<br>**true**: Hide the back button.<br>**false**: Show the back button.<br>**NOTE**<br>The back button works only when **titleMode** is set to **NavigationTitleMode.Mini**.|
51| navBarWidth<sup>9+</sup>           | [Length](ts-types.md#length)             | Width of the navigation bar.<br>Default value: **240**<br>Unit: vp<br>**NOTE**<br>This attribute is valid only when the **\<Navigation>** component is split.|
52| navBarPosition<sup>9+</sup>        | [NavBarPosition](#navbarposition9)    | Position of the navigation bar.<br>Default value: **NavBarPosition.Start**<br>**NOTE**<br>This attribute is valid only when the **\<Navigation>** component is split.|
53| mode<sup>9+</sup>                  | [NavigationMode](#navigationmode9)    | Display mode of the navigation bar.<br>Default value: **NavigationMode.Auto**<br>At the default settings, the component adapts to a single column or two columns based on the component width.<br>**NOTE**<br>Available options are **Stack**, **Split**, and **Auto**.|
54| backButtonIcon<sup>9+</sup>        | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Back button icon in the title bar. The back button in the title bar of the **\<NavDestination>** component cannot be hidden.|
55| hideNavBar<sup>9+</sup>            | 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.|
56| navDestination<sup>10+</sup>       | builder: (name: string, param: unknown) => void | Builder for a **\<NavDestination>** component.<br>**NOTE**<br>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 **\<NavDestination>** component. However, no attributes or events can be set for the custom components. Otherwise, only blank components are displayed.|
57| navBarWidthRange<sup>10+</sup>     | [[Dimension](ts-types.md#dimension10), [Dimension](ts-types.md#dimension10)] | Minimum and maximum widths of the navigation bar (valid in dual-column mode).<br>Default value: **240** for the minimum value; 40% of the component width (not greater than 432) for the maximum value<br>Unit: vp<br>Priority rules:<br>Custom value > Default value<br>Minimum value > Maximum value<br>navBar > content<br>If custom values conflict, the global value takes precedence, and the local minimum value depends on the container size.|
58| minContentWidth<sup>10+</sup>      | [Dimension](ts-types.md#dimension10)     | Minimum width of the navigation bar content area (valid in dual-column mode).<br>Default value: **360**<br>Unit: vp<br>Priority rules:<br>Custom value > Default value<br>Minimum value > Maximum value<br>navBar > content<br>If custom values conflict, the global value takes precedence, and the local minimum value depends on the container size.<br>Breakpoint calculation in Auto mode: default 600 vp = minNavBarWidth (240 vp) + minContentWidth (360 vp)|
59
60## Events
61
62| Name                                      | Description                                    |
63| ---------------------------------------- | ---------------------------------------- |
64| onTitleModeChange(callback: (titleMode: NavigationTitleMode) =&gt; void) | Called when **titleMode** is set to **NavigationTitleMode.Free** and the title bar mode changes as content scrolls.|
65| onNavBarStateChange(callback: (isVisible: boolean) =&gt; void) | Called when the navigation bar visibility status changes. The value **true** means that the navigation bar is displayed, and **false** means the opposite.|
66
67## NavPathStack<sup>10+</sup>
68
69Implements a navigation stack.
70
71### pushPath<sup>10+</sup>
72
73pushPath(info: NavPathInfo): void
74
75Pushes the navigation destination page specified by **info** to the navigation stack.
76
77**Parameters**
78
79| Name  | Type                           | Mandatory  | Description                  |
80| ---- | ----------------------------- | ---- | -------------------- |
81| info | [NavPathInfo](#navpathinfo10) | Yes   | Information about the navigation destination page.|
82
83### pushPathByName<sup>10+</sup>
84
85pushPathByName(name: string, param: unknown): void
86
87Pushes the navigation destination page specified by **name**, with the data specified by **param**, to the navigation stack.
88
89**Parameters**
90
91| Name   | Type     | Mandatory  | Description                   |
92| ----- | ------- | ---- | --------------------- |
93| name  | string  | Yes   | Name of the navigation destination page.  |
94| param | unknown | Yes   | Detailed parameters of the navigation destination page.|
95
96### pop<sup>10+</sup>
97
98pop(): NavPathInfo | undefined
99
100Pops the top element out of the navigation stack.
101
102**Return value**
103
104| Type         | Description                      |
105| ----------- | ------------------------ |
106| [NavPathInfo](#navpathinfo10) | Returns the information about the navigation destination page at the top of the stack.|
107| undefined   | Returns **undefined** if the navigation stack is empty.     |
108
109### popToName<sup>10+</sup>
110
111popToName(name: string): number
112
113Returns the navigation stack to the first navigation destination page that matches the value of **name**.
114
115**Parameters**
116
117| Name  | Type    | Mandatory  | Description                 |
118| ---- | ------ | ---- | ------------------- |
119| name | string | Yes   | Name of the navigation destination page.|
120
121**Return value**
122
123| Type    | Description                                      |
124| ------ | ---------------------------------------- |
125| 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.|
126
127### popToIndex<sup>10+</sup>
128
129popToIndex(index: number): void
130
131Returns the navigation stack to the page specified by **index**.
132
133**Parameters**
134
135| Name   | Type    | Mandatory  | Description                    |
136| ----- | ------ | ---- | ---------------------- |
137| index | number | Yes   | Index of the navigation destination page.|
138
139### moveToTop<sup>10+</sup>
140
141moveToTop(name: string): number
142
143Moves to the top of the navigation stack the first navigation destination page that matches the value of **name**.
144
145**Parameters**
146
147| Name  | Type    | Mandatory  | Description                 |
148| ---- | ------ | ---- | ------------------- |
149| name | string | Yes   | Name of the navigation destination page.|
150
151**Return value**
152
153| Type    | Description                                      |
154| ------ | ---------------------------------------- |
155| 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.|
156
157### moveIndexToTop<sup>10+</sup>
158
159moveIndexToTop(index: number): void
160
161Moves to the top of the navigation stack the navigation destination page that matches the value of **index**.
162
163**Parameters**
164
165| Name   | Type    | Mandatory  | Description                    |
166| ----- | ------ | ---- | ---------------------- |
167| index | number | Yes   | Index of the navigation destination page.|
168
169### clear<sup>10+</sup>
170
171clear(): void
172
173Clears the navigation stack.
174
175### getAllPathName<sup>10+</sup>
176
177getAllPathName(): Array<string\>
178
179Obtains the names of all navigation destination pages in the navigation stack.
180
181**Return value**
182
183| Type            | Description                        |
184| -------------- | -------------------------- |
185| Array<string\> | Names of all navigation destination pages in the navigation stack.|
186
187### getParamByIndex<sup>10+</sup>
188
189getParamByIndex(index: number): unknown | undefined
190
191Obtains the parameter information of the navigation destination page that matches the value of **index**.
192
193**Parameters**
194
195| Name   | Type    | Mandatory  | Description                    |
196| ----- | ------ | ---- | ---------------------- |
197| index | number | Yes   | Index of the navigation destination page.|
198
199**Return value**
200
201| Type       | Description                        |
202| --------- | -------------------------- |
203| unknown   | Returns the parameter information of the matching navigation destination page.|
204| undefined | Returns **undefined** if the passed index is invalid.    |
205
206### getParamByName<sup>10+</sup>
207
208getParamByName(name: string): Array<unknown\>
209
210Obtains the parameter information of all the navigation destination pages that match the value of **name**.
211
212**Parameters**
213
214| Name  | Type    | Mandatory  | Description                 |
215| ---- | ------ | ---- | ------------------- |
216| name | string | Yes   | Name of the navigation destination page.|
217
218**Return value**
219
220| Type             | Description                               |
221| --------------- | --------------------------------- |
222| Array<unknown\> | Parameter information of all the matching navigation destination pages.|
223
224### getIndexByName<sup>10+</sup>
225
226getIndexByName(name: string): Array<number\>
227
228Obtains the indexes of all the navigation destination pages that match the value of **name**.
229
230**Parameters**
231
232| Name  | Type    | Mandatory  | Description                 |
233| ---- | ------ | ---- | ------------------- |
234| name | string | Yes   | Name of the navigation destination page.|
235
236**Return value**
237
238| Type            | Description                               |
239| -------------- | --------------------------------- |
240| Array<number\> | Indexes of all the matching navigation destination pages.|
241
242### size<sup>10+</sup>
243
244size(): number
245
246Obtains the stack size.
247
248**Return value**
249
250| Type    | Description    |
251| ------ | ------ |
252| number | Stack size.|
253
254## NavPathInfo<sup>10+</sup>
255
256Provides the navigation page information.
257
258### constructor
259
260constructor(name: string, param: unknown)
261
262**Parameters**
263
264| Name   | Type     | Mandatory  | Description                   |
265| ----- | ------- | ---- | --------------------- |
266| name  | string  | Yes   | Name of the navigation destination page.  |
267| param | unknown | No   | Detailed parameters of the navigation destination page.|
268
269## NavigationMenuItem
270
271| Name    | Type           | Mandatory  | Description             |
272| ------ | ------------- | ---- | --------------- |
273| value  | string        | Yes   | Text of the menu item. Its visibility varies by the API version.<br>API version 9: visible.<br>API version 10: invisible. |
274| icon   | string        | No   | Icon path of the menu item.|
275| action | () =&gt; void | No   | Callback invoked when the menu item is selected.  |
276
277## object
278
279| Name    | Type           | Mandatory  | Description             |
280| ------ | ------------- | ---- | --------------- |
281| value  | string        | Yes   | Text of a toolbar item.  |
282| icon   | string        | No   | Icon path of a toolbar item.|
283| action | () =&gt; void | No   | Callback invoked when a toolbar item is selected.  |
284
285## ToolbarItem<sup>10+</sup>
286
287| Name        | Type                                      | Mandatory  | Description                                      |
288| ---------- | ---------------------------------------- | ---- | ---------------------------------------- |
289| value      | ResourceStr                              | Yes   | Text of a toolbar item.                           |
290| icon       | ResourceStr                              | No   | Icon path of a toolbar item.                         |
291| action     | () =&gt; void                            | No   | Callback invoked when a toolbar item is selected.                           |
292| status     | [ToolbarItemStatus](#toolbaritemstatus10) | No   | Status of a toolbar item.<br>Default value: **ToolbarItemStatus.NORMAL**|
293| activeIcon | ResourceStr                              | No   | Icon path of the toolbar item in the active state.               |
294
295## ToolbarItemStatus<sup>10+</sup>
296
297| Name      | Description                                      |
298| -------- | ---------------------------------------- |
299| 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.|
300| DISABLED | Disabled state. In this state, the toolbar item is disabled and does not allow for user interactions.|
301| 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.|
302
303## NavigationTitleMode
304
305| Name  | Description                                      |
306| ---- | ---------------------------------------- |
307| 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.<br>**NOTE**<br>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.|
308| Mini | The title is fixed at mini mode.                               |
309| Full | The title is fixed at full mode.                               |
310
311## NavigationCommonTitle<sup>9+</sup>
312
313| Name  | Type    | Mandatory  | Description    |
314| ---- | ------ | ---- | ------ |
315| main | string | Yes   | Main title.|
316| sub  | string | Yes   | Subtitle.|
317
318## NavigationCustomTitle<sup>9+</sup>
319
320| Name     | Type                                      | Mandatory  | Description      |
321| ------- | ---------------------------------------- | ---- | -------- |
322| builder | [CustomBuilder](ts-types.md#custombuilder8) | Yes   | Content of the title bar.|
323| height  | [TitleHeight](#titleheight9) \| [Length](ts-types.md#length) | Yes   | Height of the title bar.|
324
325## NavBarPosition<sup>9+</sup>
326
327| Name   | Description              |
328| ----- | ---------------- |
329| Start | When two columns are displayed, the main column is at the start of the main axis.|
330| End   | When two columns are displayed, the main column is at the end of the main axis.|
331
332## NavigationMode<sup>9+</sup>
333
334| Name | Description                                                        |
335| ----- | ------------------------------------------------------------ |
336| Stack | The navigation bar and content area are displayed independently of each other, which are equivalent to two pages.                    |
337| Split | The navigation bar and content area are displayed in different columns.<br>The values of **navBarWidthRange** are represented by [minNavBarWidth,maxNavBarWidth].<br>1. When the value of **navBarWidth** is beyond the value range specified by **navBarWidthRange**, **navBarWidth** is set according to the following rules:<br>Value of **navBarWidth** < Value of **minNavBarWidth**: The value of **navBarWidth** is changed to that of **minNavBarWidth**.<br>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**.<br>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**.<br>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).<br>2. When the value of **navBarWidth** is within the value range specified by **navBarWidthRange**, **navBarWidth** is set according to the following rules:<br>Value of **minNavBarWidth** + Value of **minContentWidth** + Divider width (1 vp) > = Component width: The value of **navBarWidth** is changed to that of **minNavBarWidth**.<br>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).<br>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. <br>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.<br>4. When the navigation bar is set to a fixed size and the component size is continuously decreased, the navigation bar is shrunk.<br>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.|
338| 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.<br>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).|
339
340## TitleHeight<sup>9+</sup>
341
342| Name         | Description                        |
343| ----------- | -------------------------- |
344| MainOnly    | Recommended height (56 vp) of the title bar when only the main title is available.     |
345| MainWithSub | Recommended height (82 vp) of the title bar when both the main title and subtitle exist.|
346
347
348>  **NOTE**
349>
350>  Among the scrollable components, only **\<List>** is supported.
351
352
353## Example
354
355### Example 1
356
357```ts
358// xxx.ets
359class A {
360  text: string = ''
361  num: number = 0
362}
363
364@Entry
365@Component
366struct NavigationExample {
367  private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
368  @State currentIndex: number = 0
369
370  @Builder NavigationTitle() {
371    Column() {
372      Text('Title')
373        .fontColor('#182431')
374        .fontSize(30)
375        .lineHeight(41)
376        .fontWeight(700)
377      Text('subtitle')
378        .fontColor('#182431')
379        .fontSize(14)
380        .lineHeight(19)
381        .opacity(0.4)
382        .margin({ top: 2, bottom: 20 })
383    }.alignItems(HorizontalAlign.Start)
384  }
385
386  @Builder NavigationMenus() {
387    Row() {
388      Image('resources/base/media/ic_public_add.svg')
389        .width(24)
390        .height(24)
391      Image('resources/base/media/ic_public_add.svg')
392        .width(24)
393        .height(24)
394        .margin({ left: 24 })
395      Image('common/ic_public_more.svg')
396        .width(24)
397        .height(24)
398        .margin({ left: 24 })
399    }
400  }
401
402  build() {
403    Column() {
404      Navigation() {
405        TextInput({ placeholder: 'search...' })
406          .width('90%')
407          .height(40)
408          .backgroundColor('#FFFFFF')
409          .margin({ top: 8 })
410
411        List({ space: 12, initialIndex: 0 }) {
412          ForEach(this.arr, (item: number) => {
413            ListItem() {
414              Text('' + item)
415                .width('90%')
416                .height(72)
417                .backgroundColor('#FFFFFF')
418                .borderRadius(24)
419                .fontSize(16)
420                .fontWeight(500)
421                .textAlign(TextAlign.Center)
422            }
423          }, (item: number) => item.toString())
424        }
425        .height(324)
426        .width('100%')
427        .margin({ top: 12, left: '10%' })
428      }
429      .title(this.NavigationTitle)
430      .menus(this.NavigationMenus)
431      .titleMode(NavigationTitleMode.Full)
432      .toolbarConfiguration([
433        {
434          value: $r("app.string.navigation_toolbar_add"),
435          icon: $r("app.media.ic_public_highlightsed")
436        },
437        {
438          value: $r("app.string.navigation_toolbar_app"),
439          icon: $r("app.media.ic_public_highlights")
440        },
441        {
442          value: $r("app.string.navigation_toolbar_collect"),
443          icon: $r("app.media.ic_public_highlights")
444        }
445      ])
446      .hideTitleBar(false)
447      .hideToolBar(false)
448      .onTitleModeChange((titleModel: NavigationTitleMode) => {
449        console.info('titleMode' + titleModel)
450      })
451    }.width('100%').height('100%').backgroundColor('#F1F3F5')
452  }
453}
454```
455
456![en-us_image_navigation](figures/en-us_image_navigation.png)
457
458
459
460### Example 2
461```ts
462// Index.ets
463import { PageOneTmp } from './PageOne'
464import { pageTwoTmp } from './PageTwo'
465import { Pages }  from './PageTwo'
466
467@Entry
468@Component
469struct NavigationExample {
470  @Provide('pageInfos') pageInfos: NavPathStack = new NavPathStack()
471
472  @Builder
473  PageMap(name: string) {
474    if (name === 'pageOne') {
475      PageOneTmp()
476    } else if (name === 'pageTwo') {
477      pageTwoTmp({ names: name, values: this.pageInfos } as Pages)
478    }
479  }
480
481  build() {
482    Navigation(this.pageInfos) {
483      Column() {
484        Button('pushPath', { stateEffect: true, type: ButtonType.Capsule })
485          .width('80%')
486          .height(40)
487          .margin(20)
488          .onClick(() => {
489            this.pageInfos.pushPath({ name:'pageOne'}) // Push the navigation destination page specified by name to the navigation stack.
490          })
491      }
492    }.title('NavIndex').navDestination(this.PageMap)
493  }
494}
495```
496```ts
497// PageOne.ets
498class TmpClass{
499  count:number=10
500}
501@Component
502export struct PageOneTmp {
503  @Consume('pageInfos') pageInfos: NavPathStack;
504
505  build() {
506    NavDestination() {
507      Column() {
508        Button('pushPathByName', { stateEffect: true, type: ButtonType.Capsule })
509          .width('80%')
510          .height(40)
511          .margin(20)
512          .onClick(() => {
513            let tmp = new TmpClass()
514            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.
515          })
516        Button('popToname', { stateEffect: true, type: ButtonType.Capsule })
517          .width('80%')
518          .height(40)
519          .margin(20)
520          .onClick(() => {
521            this.pageInfos.popToName('pageTwo') // Return the navigation stack to the first navigation destination page that matches the value of name.
522            console.log('popToName' + JSON.stringify(this.pageInfos), 'Return value' + JSON.stringify(this.pageInfos.popToName('pageTwo')))
523          })
524        Button('popToIndex', { stateEffect: true, type: ButtonType.Capsule })
525          .width('80%')
526          .height(40)
527          .margin(20)
528          .onClick(() => {
529            this.pageInfos.popToIndex(1) // Return the navigation stack to the navigation destination page that matches the value of index.
530            console.log('popToIndex' + JSON.stringify(this.pageInfos))
531          })
532        Button('moveToTop', { stateEffect: true, type: ButtonType.Capsule })
533          .width('80%')
534          .height(40)
535          .margin(20)
536          .onClick(() => {
537            this.pageInfos.moveToTop('pageTwo') // Move to the top of the navigation stack the first navigation destination page that matches the value of name.
538            console.log('moveToTop' + JSON.stringify(this.pageInfos), 'Return value' + JSON.stringify(this.pageInfos.moveToTop('pageTwo')))
539          })
540        Button('moveIndexToTop', { stateEffect: true, type: ButtonType.Capsule })
541          .width('80%')
542          .height(40)
543          .margin(20)
544          .onClick(() => {
545            this.pageInfos.moveIndexToTop(1) // Move to the top of the navigation stack the navigation destination page that matches the value of index.
546            console.log('moveIndexToTop' + JSON.stringify(this.pageInfos))
547          })
548        Button('clear', { stateEffect: true, type: ButtonType.Capsule })
549          .width('80%')
550          .height(40)
551          .margin(20)
552          .onClick(() => {
553            this.pageInfos.clear() // Clear the navigation stack.
554          })
555        Button('get', { stateEffect: true, type: ButtonType.Capsule })
556          .width('80%')
557          .height(40)
558          .margin(20)
559          .onClick(() => {
560            console.log('-------------------')
561            console.log('Obtained the names of all pages in the navigation stack', JSON.stringify(this.pageInfos.getAllPathName()))
562            console.log('Obtained parameter information of the navigation destination page specified by index', JSON.stringify(this.pageInfos.getParamByIndex(1)))
563            console.log('Obtained parameter information of all the navigation destination pages specified by name', JSON.stringify(this.pageInfos.getParamByName('pageTwo')))
564            console.log('Obtained the index information of all the navigation destination pages specified by name', JSON.stringify(this.pageInfos.getIndexByName('pageOne'))))
565            console.log ('Obtained the stack size', JSON.stringify (this.pageInfos.size ()))
566          })
567      }.width('100%').height('100%')
568    }.title('pageOne')
569    .onBackPressed(() => {
570      const popDestinationInfo = this.pageInfos.pop() // Pop the top element out of the navigation stack.
571      console.log ('pop' + 'Return value' + JSON.stringify (popDestinationInfo))
572      return true
573    })
574  }
575}
576```
577```ts
578// PageTwo.ets
579export class Pages {
580  names: string = ""
581  values: NavPathStack | null = null
582}
583
584@Builder
585export function pageTwoTmp(info: Pages) {
586  NavDestination() {
587    Column() {
588      Button('pushPathByName', { stateEffect: true, type: ButtonType.Capsule })
589        .width('80%')
590        .height(40)
591        .margin(20)
592        .onClick(() => {
593          (info.values as NavPathStack).pushPathByName('pageOne', null)
594        })
595    }.width('100%').height('100%')
596  }.title('pageTwo')
597  .onBackPressed(() => {
598    (info.values as NavPathStack).pop()
599    return true
600  })
601}
602```
603![navigation.gif](figures/navigation.gif)
604