9.0 Released! → Native ESM runtimes 🚀, Vite support ⚡️, multi-window apps and more...
Read Announcement

Showing a modal

To show a modal, call the showModal method on a View instance and pass it the path to the modal view file:

Note

If your modal does not appear when tapping the button, confirm you set the correct path and the modal page exists. showModal does not throw an error when the provided path doesn't exist.

Closing a modal

To close a modal, call the closeModal method of any View from the modal.

For passing data back to the parent, see Passing Data.

Passing data

Modals are often used for prompting the user for input, this requires passing data between the parent and the modal.

From parent to modal

To pass data to the modal in core TypeScript, provide it in the context field of ShowModalOptions. In Angular, pass data in the data option of NativeDialog.open(...).

In the core TypeScript modal page, listen to the shownModally event to access the context:

xml
<!-- details-page.xml -->
<Page shownModally="onShownModally"/>
ts
// details-page.ts
import { ShownModallyData } from '@nativescript/core'

// optional strong type for the context
export type ExampleModalContext = {
  name: string
}

export function onShownModally(args: ShownModallyData) {
  const context = args.context as ExampleModalContext
  console.log(context.name) // 'John Doe'
}

From modal to parent

When closing a modal, you can optionally pass data back to the parent. In core TypeScript, use closeCallback in ShowModalOptions. In Angular, subscribe to ref.afterClosed() and close with dialogRef.close(data).

In the core TypeScript modal page, listen to the shownModally event to access the context.

xml
<Page shownModally="onShownModally">
  <StackLayout>
    <!-- ... -->
    <TextField text="{{ name }}" />
    <Button text="Change Name" tap="onChangeName"></Button>
    <Button text="Cancel" tap="onCancel"></Button>
  </StackLayout>
</Page>
ts
import {
  fromObject,
  Page,
  Button,
  View,
  ShownModallyData,
  EventData,
} from '@nativescript/core'

// optional strong type for the context
export type ExampleModalContext = {
  name: string
}

export type ExampleModalResult = {
  newName: string
}

export function onShownModally(args: ShownModallyData) {
  const page = args.object as Page
  const incomingContext = args.context as ExampleModalContext

  const bindingContext = fromObject({
    ...incomingContext,
    onChangeName(args: EventData) {
      const button = args.object as Button
      button.closeModal({
        newName: bindingContext.name, // 'Jane Doe'
      } as ExampleModalResult)
    },
    onCancel(args: EventData) {
      const view = args.object as View
      view.closeModal()
    },
  })
  page.bindingContext = bindingContext
}

Additional Resources