|
| 1 | +--- |
| 2 | +title: Navigation using Modals |
| 3 | +description: Navigation using modals - detached from the current backstack. |
| 4 | +contributos: |
| 5 | + - Ombuweb |
| 6 | + - rigor789 |
| 7 | +--- |
| 8 | + |
| 9 | +## Showing a modal |
| 10 | + |
| 11 | +To show a modal, call the [showModal](https://docs.nativescript.org/api-reference/classes/view#showmodal) method on a [View](https://docs.nativescript.org/api-reference/classes/view) instance and pass it the path to the modal view file: |
| 12 | + |
| 13 | +```xml |
| 14 | +<Button text="View details" tap="onTap" /> |
| 15 | +``` |
| 16 | + |
| 17 | +```ts |
| 18 | +onTap(args: EventData) { |
| 19 | + const button = args.object as Button |
| 20 | + button.showModal("details-page") |
| 21 | +} |
| 22 | +``` |
| 23 | + |
| 24 | +## Closing a modal |
| 25 | + |
| 26 | +To close a modal, call the `closeModal` method of any `View` from the modal. Optionally pass it data you want to access in the parent page: |
| 27 | + |
| 28 | +```xml |
| 29 | +<Button text="Close" tap="onTap" /> |
| 30 | +``` |
| 31 | + |
| 32 | +```ts |
| 33 | +onTap(args: EventData) { |
| 34 | + const button = args.object as Button |
| 35 | + button.closeModal({ |
| 36 | + name: 'John Doe - EDITED', |
| 37 | + }) |
| 38 | +} |
| 39 | +``` |
| 40 | + |
| 41 | +## Passing data to and from a modal |
| 42 | + |
| 43 | +Passing data can be done by passing a `context` in the `showModal` options parameter. |
| 44 | + |
| 45 | +```ts |
| 46 | +const options: ShowModalOptions = { |
| 47 | + context: { name: 'John Doe' }, |
| 48 | + closeCallback(args: { name: string }) { |
| 49 | + console.log('Modal closed', args.name) |
| 50 | + }, |
| 51 | +} |
| 52 | +// ... |
| 53 | +button.showModal('details-page', options) |
| 54 | +``` |
| 55 | + |
| 56 | +To access the data in the modal, handle the `shownModally` event, and access it via `args.context`. |
| 57 | + |
| 58 | +```xml |
| 59 | +<Page shownModally="onShownModally"> |
| 60 | + <StackLayout> |
| 61 | + <TextField text="{{ name }}" /> |
| 62 | + <Button text="Close" tap="onClose"/> |
| 63 | + </StackLayout> |
| 64 | +</Page> |
| 65 | +``` |
| 66 | + |
| 67 | +```ts |
| 68 | +import { |
| 69 | + fromObject, |
| 70 | + Page, |
| 71 | + Button, |
| 72 | + ShownModallyData, |
| 73 | + EventData, |
| 74 | +} from '@nativescript/core' |
| 75 | + |
| 76 | +export function onShownModally(args: ShownModallyData) { |
| 77 | + const page = args.object as Page |
| 78 | + const context = fromObject({ |
| 79 | + ...args.context, |
| 80 | + onClose(args: EventData) { |
| 81 | + const button = args.object as Button |
| 82 | + button.closeModal({ |
| 83 | + name: context.name, // 'John Doe - EDITED' |
| 84 | + }) |
| 85 | + }, |
| 86 | + }) |
| 87 | + page.bindingContext = context |
| 88 | +} |
| 89 | +``` |
0 commit comments