Important note

This is a community project

Svelte Native is developed by members of the the Svelte community who wish to have the same smooth development experience on mobile devices as they have on the web. This project is not an officially supported product of either the NativeScript or Svelte projects.

Yet.

Introduction

What is NativeScript?

NativeScript is an open-source framework to develop apps on the Apple iOS and Android platforms. It is open source and can be found on github

What is Svelte?

Svelte is a radical new approach to building user interfaces. Whereas traditional frameworks like React and Vue do the bulk of their work in the browser, Svelte shifts that work into a compile step that happens when you build your app.

Instead of using techniques like virtual DOM diffing, Svelte writes code that surgically updates the DOM when the state of your app changes.

What is Svelte Native

Svelte Native is a tool for building mobile applications. It combines NativeScript's access to the native platform views and Svelte's fast and efficient view updates to allow you to build native mobile experiences using tools such as HTML, CSS and Javascript.

Read the introductory blog post.

NativeScript + Svelte = Svelte Native

Getting Started

Quick Start

Install Nativescript

Svelte-Native works on top of NativeScript. To install NativeScript:

$ npm install -g nativescript

Check it worked by running tns

Success

Install the NativeScript Playground app

Svelte-Native really is native, so it needs a mobile device to run. The build setup for iOS or Android can be a pain, so the wizards at Progress have created the NativeScript playground app. This allows us to run Svelte-Native application code without having to build the full mobile application.

Get if rom the App Store Get it from Google Play

Create a new Svelte-Native app

The easiest way to get started is to use the latest template app

$ degit halfnelson/svelte-native-template myapp

A fresh svelte-native app will be found in the myapp folder

Launch It

Launch your app with:

$ cd myapp
$ tns preview --bundle

You will need to scan the ascii art QR code using the "Playground" app you installed previously.

Running App

Advanced Install

To compile your apps for distribution, you will need to use setup your system for local compilation.

Svelte-Native runs on top of an unmodified NativeScript platform. Installation instructions for your operating system can be found in the Native Script Guide

Check you have the NativeScript build environment configured correctly by using the Nativescript doctor command:

$  tns doctor

Once that is happy you can do a full compile and launch of your application with

$ tns run android --bundle

or

$ tns run ios --bundle

Navigation/Routing

Since Svelte Native is a thin bridge between Svelte and NativeScript. It is best if you familiarize yourself with the core concept of routing in NativeScript

Routing in Svelte Native is designed to be very similar and the svelte-native module exposes the following functions:

navigate

Specify the destination page with the mandatory page option. This takes a Svelte component class.

App.svelte
<page>
	<actionBar title="Master" />
	<stackLayout>
		<button text="To Details directly" on:tap="{ () => navigate({ page: Detail }) }" />
	</stackLayout>
</page>

<script>
	import Detail from './Detail.svelte'
	import { navigate } from 'svelte-native'
</script>

Passing props to the target component

You can specify the props used to create the Svelte component using the props option.

App.svelte
<page>
	<actionBar title="Master" />
	<stackLayout>
		<button text="To Details directly" on:tap="{showDetailWithProps}" />
	</stackLayout>
</page>

<script>
	import Detail from './Detail.svelte'
	import { navigate } from 'svelte-native'

	function showDetailWithProps() {
		navigate({ 
			page: Detail,
			props: { message: "Hello from master" }
		});
	}
</script>

Specifying a Frame

Each <frame> element has its own navigation stack. If you are using multiple frames, you may want to specify in which frame the navigation will occur. For example, having a button in the side bar that changes the page in the main area. You can do this by adding the frame option:

navigate({ 
	page: Detail,
	frame: '<id, or ref, or instance>'
});

The value for the frame option can be one of the following:

  • the id of the <frame> component (for example: <frame id="main-frame">)
  • a reference to the <frame> (for example: <frame bind:this="{mainFrame}">)
  • a NativeScript Frame instance.

If no frame is specified, the navigation will occur on the topmost frame.

Other Options

For more information about the options that you can pass, see NavigationEntry.

goBack

To navigate back to a previous page, use the goBack function.

App.svelte
<page>
  <actionBar title="Detail"/>
  <stackLayout>
	<button text="Back to Master" on:tap="{goBack}" />
  </stackLayout>
</page>

<script>
import { goBack } from 'svelte-native'
</script>

To cause the back to happen on another frame, pass in a frame reference or id to the frame option.

  goBack({frame: 'sub-nav-frame'})

goBack by default goes back to the previous page, you can go back multiple pages if you specify a page reference in options.

  goBack({to: options_page_ref})

showModal

To show a page or component modally use the showModal function. Specify the page to open using the page option and props using the props option (just like in navigate)

App.svelte
<page>
   <actionBar title="Master" />
   <stackLayout>
	 <button text="Open Modal" on:tap="{launchModal}" />
   </stackLayout>
</page>


<script>
	import DetailPage from './DetailPage.svelte'
	import { showModal } from 'svelte-native'
	function launchModal() {
		showModal({ page: DetailPage, props: { msg: 'hi' } })
	}
</script>
DetailPage.svelte
<frame id="detail-page-frame">
  <page>

  </page>
</frame>

The other options available correspond directly to those in ShowModalOptions and are passed through to the underlying NativeScript showModal method.

The showModal function returns a promise which resolves to whatever is passed to closeModal

NOTE The modal is opened in a new navigation context. If you want to allow navigation within the modal, or show an action bar, you will need to wrap the target page in a frame element. If you don't need any navigation within the modal then this won't be necessary.

closeModal

The closeModal function closes the current modal view and optionally returns a value to the caller of the original showModal via a promise result.

App.svelte
<page>
   <actionBar title="Master" />
   <stackLayout>
	 <button text="Open Modal" on:tap="{launchModal}" />
	 <label text="{modalResult}" />
   </stackLayout>
</page>
<script>
	import DetailPage from './DetailPage.svelte'
	import { showModal } from 'svelte-native'

	let modalResult = "Waiting for modal"
	async function launchModal() {
		let result = await showModal({ page: DetailPage, props: { msg: 'hi' } })
		modalResult = `got result: ${result}`
	}
</script>
DetailPage.svelte
<frame id="detail-page-frame">
  <page>
	<button text="Close me" on:tap="{ () => closeModal('hi from modal') }" />
  </page>
</frame>
<script>
  import { closeModal } from 'svelte-native'
</script>

Utilities

Template Component

The <Template> svelte component lets you define markup that is reused as a template. It is currently used to render listItems in the <listView> component.

Basic usage

<page>
  <listView items="{items}">
	<Template let:item={i}>
	  <label text="{i}" />
	</Template>
  </listView>
</page>
<script>
  import { Template } from 'svelte-native/components'
  let items = ['one', 'two', 'three']
</script>

NOTE The template element here has a capital T and is imported from svelte-native/components. This is because it is a Svelte component not a NativeScript element.

Advanced usage

You can use Template to implement custom NativeScript elements that require a template or multiple templates.

When Template is rendered by svelte, it outputs a special DOM element called template which has a component attribute. Implementations such as svelte native's binding to listView look for the template elements and use the component to instantiate and render the template content.

Any extra properties added to the Template component are passed down and added to the template DOM element.

For concrete example of this pattern see svelte native's listView element source

Property Element

Some NativeScript controls have properties that expect NativeScript views as values. To make this possible using markup, Svelte Native introduces the property element. This element works like the ones in the NativeScript core documentation and set some property of their parent view with the value of the first child of the property element. The tag name is the name of the parent element followed by the property name. For example <page.actionbar> would set the actionbar property of the parent page element.

An Example

The <radSideDrawer> component is part of the Progress NativeScript UI package.

The <radSideDrawer> component requires the drawerContent and mainContent properties to be set to View instances. Using Property Elements, you can do this with a few lines of code:

<radSideDrawer>
  <radSideDrawer.drawerContent>
	<stackLayout />
  </radSideDrawer.drawerContent>
  <radSideDrawer.mainContent>
	<stackLayout />
  </radSideDrawer.mainContent>
</radSideDrawer>

Without the Property Elements, you need to go a more tedious and error-prone route:

<radSideDrawer bind:this="{drawer}">
  <stackLayout bind:this="{drawerContent}" />
  <stackLayout bind:this="{mainContent}" />
</radSideDrawer>
  import { onMount } from 'svelte'

  let drawer
  let drawerContent
  let mainContent

  onMount(() => {
	drawer.nativeView.mainContent = mainContent.nativeView
	drawer.nativeView.drawerContent = drawerContent.nativeView
  })

Layouts

AbsoluteLayout

The <absoluteLayout> container is the simplest layout container in NativeScript.

<absoluteLayout> has the following behavior:

  • Uses a pair of absolute left/top coordinates to position its children.
  • Doesn't enforce any layout constraints on its children.
  • Doesn't resize its children at runtime when its size changes.

Examples

A grid-like layout

The following example creates a simple grid. For more information about creating grid layouts, see GridLayout.

<absoluteLayout backgroundColor="#3c495e">
  <label text="10,10" left="10" top="10" width="100" height="100" backgroundColor="#4383b8"/>
  <label text="120,10" left="120" top="10" width="100" height="100" backgroundColor="#4383b8"/>
  <label text="10,120" left="10" top="120" width="100" height="100" backgroundColor="#4383b8"/>
  <label text="120,120" left="120" top="120" width="100" height="100" backgroundColor="#4383b8"/>
</absoluteLayout>

Overlapping elements

The following example creates a group of overlapping items.

<absoluteLayout backgroundColor="#3c495e">
  <label text="10,10" left="10" top="10" width="100" height="100" backgroundColor="#286290"/>
  <label text="30,40" left="30" top="40" width="100" height="100" backgroundColor="#4383b8"/>
</absoluteLayout>

Additional children props

When an element is a direct child of <absoluteLayout>, you can work with the following additional properties.

Name Type Description
top Number Gets or sets the distance, in pixels, between the top edge of the child and the top edge of its parent.
left Number Gets or sets the distance, in pixels, between the left edge of the child and the left edge of its parent.

DockLayout

<DockLayout> is a layout container that lets you dock child elements to the sides or the center of the layout.

<DockLayout> has the following behavior:

  • Uses the dock property to dock its children to the left, right, top, bottom or center of the layout.
    To dock a child element to the center, it must be the last child of the container and you must set the stretchLastChild property of the parent to true.
  • Enforces layout constraints to its children.
  • Resizes its children at runtime when its size changes.

Examples

Dock to every side without stretching the last child

The following example creates a frame-like layout consisting of 4 elements, position at the 4 edges of the screen.

<dockLayout stretchLastChild="false" backgroundColor="#3c495e">
  <label text="left" dock="left" width="40" backgroundColor="#4383b8"/>
  <label text="top" dock="top" height="40" backgroundColor="#286290"/>
  <label text="right" dock="right" width="40" backgroundColor="#4383b8"/>
  <label text="bottom" dock="bottom" height="40" backgroundColor="#286290"/>
</dockLayout>

Dock to every side and stretch the last child

The following example shows how stretchLastChild affects the positioning of child elements in a DockLayout container. The last child (bottom) is stretched to take up all the remaining space after positioning the first three elements.

<dockLayout stretchLastChild="true" backgroundColor="#3c495e">
  <label text="left" dock="left" width="40" backgroundColor="#4383b8"/>
  <label text="top" dock="top" height="40" backgroundColor="#286290"/>
  <label text="right" dock="right" width="40" backgroundColor="#4383b8"/>
  <label text="bottom" dock="bottom" backgroundColor="#1c486b"/>
</dockLayout>

Dock to every side and the center

The following example creates a <dockLayout> of 5 elements. The first four wrap the center element in a frame.

<dockLayout stretchLastChild="true" backgroundColor="#3c495e">
  <label text="left" dock="left" width="40" backgroundColor="#4383b8"/>
  <label text="top" dock="top" height="40" backgroundColor="#286290"/>
  <label text="right" dock="right" width="40" backgroundColor="#4383b8"/>
  <label text="bottom" dock="bottom" height="40" backgroundColor="#286290"/>
  <label text="center" backgroundColor="#1c486b" />
</dockLayout>

Dock multiple children to the same side

The following example creates a single line of 4 elements that stretch across the entire height and width of the screen.

<dockLayout stretchLastChild="true" backgroundColor="#3c495e">
  <label text="left 1" dock="left" width="40" backgroundColor="#4383b8"/>
  <label text="left 2" dock="left" width="40" backgroundColor="#286290"/>
  <label text="left 3" dock="left" width="40" backgroundColor="#1c486b"/>
  <label text="last child" backgroundColor="#4383b8"/>
</dockLayout>

Props

Name Type Description
stretchLastChild Boolean Enables or disables stretching the last child to fit the remaining space.

Additional children props

When an element is a direct child of <DockLayout>, you can work with the following additional properties.

Name Type Description
dock String Specifies which side to dock the element to.
Valid values: top, right, bottom, or left.

FlexboxLayout

<FlexboxLayout> is a layout container that provides a non-exact implementation of the CSS Flexbox layout. This layout lets you arrange child components both horizontally and vertically.

Examples

Default flex layout

The following example creates a row of three equally-sized elements that span across the entire height of the screen.

<flexboxLayout backgroundColor="#3c495e">
  <label text="first" width="70" backgroundColor="#4383b8"/>
  <label text="second" width="70" backgroundColor="#1c486b"/>
  <label text="third" width="70" backgroundColor="#286290"/>
</flexboxLayout>

Column flex layout

The following example creates a column of three equally-sized elements that span across the entire width of the screen.

<flexboxLayout flexDirection="column" backgroundColor="#3c495e">
  <label text="first" height="70" backgroundColor="#4383b8"/>
  <label text="second" height="70" backgroundColor="#1c486b"/>
  <label text="third" height="70" backgroundColor="#286290"/>
</flexboxLayout>

Row flex layout with items aligned to flex-start

The following example creates a row of three items placed at the top of the screen. Items are placed in the order they were declared in.

<flexboxLayout alignItems="flex-start" backgroundColor="#3c495e">
  <label text="first" width="70" height="70" backgroundColor="#4383b8"/>
  <label text="second" width="70" height="70" backgroundColor="#1c486b"/>
  <label text="third" width="70" height="70" backgroundColor="#286290"/>
</flexboxLayout>

Row flex layout with custom order

The following example creates a row of three items placed at the top of the screen. Items are placed in a customized order.

<flexboxLayout alignItems="flex-start" backgroundColor="#3c495e">
  <label text="first" order="2" width="70" height="70" backgroundColor="#4383b8"/>
  <label text="second" order="3" width="70" height="70" backgroundColor="#1c486b"/>
  <label text="third" order="1" width="70" height="70" backgroundColor="#286290"/>
</flexboxLayout>

Row flex layout with wrapping

The following example creates four items with enabled line wrapping. When the row runs out of space, the container wraps the last item on a new line.

<flexboxLayout flexWrap="wrap" backgroundColor="#3c495e">
  <label text="first" width="30%" backgroundColor="#4383b8"/>
  <label text="second" width="30%" backgroundColor="#1c486b"/>
  <label text="third" width="30%" backgroundColor="#286290"/>
  <label text="fourth" width="30%" backgroundColor="#286290"/>
</flexboxLayout>

Column flex layout with reverse order and items with a different alignSelf

The following example shows how to use:

  • flexDirection to place items in a column, starting from the bottom.
  • justifyContent to create equal spacing between the vertically placed items.
  • alignSelf to modify the position of items across the main axis.
<flexboxLayout flexDirection="column-reverse"
			   justifyContent="space-around" backgroundColor="#3c495e">
  <label text="first" height="70" backgroundColor="#4383b8"/>
  <label text="second" alignSelf="center" width="70" height="70" backgroundColor="#1c486b"/>
  <label text="third\nflex-end" alignSelf="flex-end" width="70" height="70" backgroundColor="#286290"/>
  <label text="fourth" height="70" backgroundColor="#286290"/>
</flexboxLayout>

Props

Name Type Description
flexDirection String Sets the direction for placing child elements in the flexbox container.
Valid values:
row (horizontal, left to right),
row-reverse (horizontal, right to left),
column (vertical, top to bottom), and
column-reverse (vertical, bottom to top).
Default value: row.
flexWrap String Sets whether child elements are forced in a single line or can flow into multiple lines. If set to multiple lines, also defines the cross axis which determines the direction new lines are stacked in.
Valid values:
nowrap (single line which may cause the container to overflow),
wrap (multiple lines, direction is defined by flexDirection),and
wrap-reverse (multiple lines, opposite to the direction defined by flexDirection).
Default value: nowrap.
justifyContent String Sets the alignment of child elements along the main axis. You can use it to distribute leftover space when all the child elements on a line are inflexible or are flexible but have reached their maximum size. You can also use it to control the alignment of items when they overflow the line.
Valid values:
flex-start (items are packed toward the start line),
flex-end (items are packed toward the end line),
center (items are centered along the line),
space-between (items are evenly distributed on the line; first item is on the start line, last item on the end line), and
space-around (items are evenly distributed on the line with equal space around them).
Default value: flex-start.
alignItems String (Android-only) Sets the alignment of child elements along the cross axis on the current line. Acts as justifyContent for the cross axis.
Valid values:
flex-start (cross-start margin edge of the items is placed on the cross-start line),
flex-end (cross-end margin edge of the items is placed on the cross-end line),
center (items are centered оn the cross axis),
baseline (the item baselines are aligned), and
stretch (items are stretched to fill the container but respect min-width and max-width).
Default value: stretch.
alignContent String Sets how lines are aligned in the flex container on the cross axis, similar to how justifyContent aligns individual items within the main axis.
This property has no effect when the flex container has only one line.
Valid values:
flex-start (lines are packed to the start of the container),
flex-end (lines are packed to the end of the container),
center (lines are packed to the center of the container),
space-between (lines are evenly distributed; the first line is at the start of the container while the last one is at the end),
space-around (lines are evenly distributed with equal space between them), and
stretch (lines are stretched to take up the remaining space).
Default value: stretch.

Additional children props

When an element is a direct child of <FlexboxLayout>, you can work with the following additional properties.

Name Type Description
order Number Sets the order in which child element appear in relation to one another.
flexGrow Number Indicates that the child should grow in size, if necessary. Sets how much the child will grow in proportion to the rest of the child elements in the flex container.
flexShrink Number Indicates that the child should shrink when the row runs out of space. Sets how much the flex item will shrink in proportion to the rest of the child elements in the flex container. When not specified, its value is set to 1.
alignSelf String (Android-only) Overrides the alignItems value for the child.
Valid values:
flex-start (cross-start margin edge of the item is placed on the cross-start line),
flex-end (cross-end margin edge of the item is placed on the cross-end line),
center (item is centered on the cross axis),
baseline (the item baselines are aligned), and
stretch (items is stretched to fill the container but respects min-width and max-width).
Default value: stretch.
flexWrapBefore Boolean When true, forces the item to wrap onto a new line. This property is not part of the official Flexbox specification.
Default value: false.

GridLayout

<GridLayout> is a layout container that lets you arrange its child elements in a table-like manner.

The grid consists of rows, columns, and cells. A cell can span one or more rows and one or more columns. It can contain multiple child elements which can span over multiple rows and columns, and even overlap each other.

By default, <GridLayout> has one column and one row. You can add columns and rows by configuring the columns and the rows properties. In these properties, you need to set the number of columns and rows and their width and height. You set the number of columns by listing their widths, separated by a comma. You set the number of rows by listing their heights, separated by a comma.

You can set a fixed size for column width and row height or you can create them in a responsive manner:

  • An absolute number: Indicates a fixed size.
  • auto: Makes the column as wide as its widest child or makes the row as tall as its tallest child.
  • *: Takes as much space as available after filling all auto and fixed size columns or rows.

Examples

Grid layout with fixed sizing

The following example creates a simple 2-by-2 grid with fixed column widths and row heights.

<gridLayout columns="115, 115" rows="115, 115">
  <label text="0,0" row="0" col="0" backgroundColor="#4383b8"/>
  <label text="0,1" row="0" col="1" backgroundColor="#1c486b"/>
  <label text="1,0" row="1" col="0" backgroundColor="#286290"/>
  <label text="1,1" row="1" col="1" backgroundColor="#4383b8"/>
</gridLayout>

Grid layout with star sizing

The following example creates a grid with responsive design, where space is alotted proportionally to child elements.

<gridLayout columns="*, 2*" rows="2*, 3*" backgroundColor="#3c495e">
  <Label text="0,0" row="0" col="0" backgroundColor="#4383b8"/>
  <Label text="0,1" row="0" col="1" backgroundColor="#1c486b"/>
  <Label text="1,0" row="1" col="0" backgroundColor="#286290"/>
  <Label text="1,1" row="1" col="1" backgroundColor="#4383b8"/>
</gridLayout>

Grid layout with fixed and auto sizing

The following example create a grid with one auto-sized column and one column with fixed size. Rows have a fixed height.

<gridLayout columns="80, auto" rows="80, 80" backgroundColor="#3c495e">
  <label text="0,0" row="0" col="0" backgroundColor="#4383b8"/>
  <label text="0,1" row="0" col="1" backgroundColor="#1c486b"/>
  <label text="1,0" row="1" col="0" backgroundColor="#286290"/>
  <label text="1,1" row="1" col="1" backgroundColor="#4383b8"/>
</gridLayout>

Grid layout with mixed sizing and merged cells

The following example creates a complex grid with responsive design, mixed width and height settings, and some merged cells.

<gridLayout columns="40, auto, *" rows="40, auto, *" backgroundColor="#3c495e">
  <label text="0,0" row="0" col="0" backgroundColor="#4383b8"/>
  <label text="0,1" row="0" col="1" colSpan="2" backgroundColor="#1c486b"/>
  <label text="1,0" row="1" col="0" rowSpan="2" backgroundColor="#286290"/>
  <label text="1,1" row="1" col="1" backgroundColor="#4383b8"/>
  <label text="1,2" row="1" col="2" backgroundColor="#286290"/>
  <label text="2,1" row="2" col="1" backgroundColor="#1c486b"/>
  <label text="2,2" row="2" col="2" backgroundColor="#4383b8"/>
</gridLayout>

Props

Name Type Description
columns String A string value representing column widths delimited with commas.
Valid values: an absolute number, auto, or *.
A number indicates an absolute column width. auto makes the column as wide as its widest child. * makes the column occupy all available horizontal space. The space is proportionally divided over all star-sized columns. You can set values such as 3* and 5* to indicate a ratio of 3:5 in sizes.
rows String A string value representing row heights delimited with commas.
Valid values: an absolute number, auto, or *.
A number indicates an absolute row height. auto makes the row as tall as its tallest child. * makes the row occupy all available vertical space. The space is proportionally divided over all star-sized rows. You can set values such as 3* and 5* to indicate a ratio of 3:5 in sizes.

Additional children props

When an element is a direct child of <GridLayout>, you can work with the following additional properties.

Name Type Description
row Number Specifies the row for this element. Combined with a col property, specifies the cell coordinates of the element.
The first row is indicated by 0.
col Number Specifies the column for the element. Combined with a row property, specifies the cell coordinates of the element.
The first column is indicated by 0.
rowSpan Number Specifies the number of rows which this element spans across.
colSpan Number Specifies the number of columns which this element spans across.

StackLayout

<stackLayout> is a layout container that lets you stack the child elements vertically (default) or horizontally.

Examples

Default stacking

The following example creates a vertical stack of 3 equally-sized elements. Items are stretched to cover the entire width of the screen. Items are placed in the order they were declared in.

<stackLayout backgroundColor="#3c495e">
  <label text="first" height="70" backgroundColor="#4383b8"/>
  <label text="second" height="70" backgroundColor="#286290"/>
  <label text="third" height="70" backgroundColor="#1c486b"/>
</stackLayout>

Horizontal stacking

The following example creates a horizontal stack of 3 equally-sized elements. Items are stretched to cover the entire height of the screen. Items are placed in the order they were declared in.

<stackLayout orientation="horizontal" backgroundColor="#3c495e">
  <label text="first" width="70" backgroundColor="#4383b8"/>
  <label text="second" width="70" backgroundColor="#286290"/>
  <label text="third" width="70" backgroundColor="#1c486b"/>
</stackLayout>

Stack layout with horizontally aligned children

The following example creates a diagonal stack of items with responsive sizes. Items are vertically stacked.

<stackLayout backgroundColor="#3c495e">
  <label text="left" horizontalAlignment="left"
		 width="33%" height="70" backgroundColor="#4383b8"/>
  <label text="center" horizontalAlignment="center"
		 width="33%" height="70" backgroundColor="#286290"/>
  <label text="right" horizontalAlignment="right"
		 width="33%" height="70" backgroundColor="#1c486b"/>
  <label text="stretch" horizontalAlignment="stretch"
		 height="70" backgroundColor="#4383b8"/>
</stackLayout>

Horizontal stack layout with vertically aligned children

The following example creates a diagonal stack of items with responsive sizes. Items are horizontally stacked.

<stackLayout orientation="horizontal" backgroundColor="#3c495e">
  <label text="top" verticalAlignment="top"
		 width="70" height="33%" backgroundColor="#4383b8"/>
  <label text="center" verticalAlignment="center"
		 width="70" height="33%" backgroundColor="#286290"/>
  <label text="bottom" verticalAlignment="bottom"
		 width="70" height="33%" backgroundColor="#1c486b"/>
  <label text="stretch" verticalAlignment="stretch"
		 width="70" backgroundColor="#4383b8"/>
</stackLayout>

Props

Name Type Description
orientation String Specifies the stacking direction.
Valid values: vertical and horizontal.
Default value: vertical.

WrapLayout

<WrapLayout> is a layout container that lets you position items in rows or columns, based on the orientation property. When the space is filled, the container automatically wraps items onto a new row or column.

Examples

Default wrap layout

The following example creates a row of equally-sized items. When the row runs out of space, the container wraps the last item on a new row.

<wrapLayout backgroundColor="#3c495e">
  <label text="first" width="30%" height="30%" backgroundColor="#4383b8"/>
  <label text="second" width="30%" height="30%" backgroundColor="#1c486b"/>
  <label text="third" width="30%" height="30%" backgroundColor="#286290"/>
  <label text="fourth" width="30%" height="30%" backgroundColor="#286290"/>
</wrapLayout>

Vertical wrap layout

The following example creates a column of equally-sized items. When the row runs out of space, the container wraps the last item on a new column.

<wrapLayout orientation="vertical" backgroundColor="#3c495e">
  <label text="first" width="30%" height="30%" backgroundColor="#4383b8"/>
  <label text="second" width="30%" height="30%" backgroundColor="#1c486b"/>
  <label text="third" width="30%" height="30%" backgroundColor="#286290"/>
  <label text="fourth" width="30%" height="30%" backgroundColor="#286290"/>
</wrapLayout>

Props

Name Type Description
orientation String Specifies the stacking direction.
Valid values: horizontal (arranges items in rows) and vertical (arranges items in columns).
Default value: horizontal.
itemWidth Number Sets the width used to measure and layout each child.
Default value: Number.NaN, which does not restrict children.
itemHeight Number Sets the height used to measure and layout each child.
Default value is Number.NaN, which does not restrict children.

ActionBars

ActionBar

<actionBar> is a UI component that provides a toolbar at the top of the activity window.

This component is the NativeScript abstraction for the Android app bar and the iOS navigation bar.

Using a title

<actionBar title="MyApp" />

Using a custom title view

<actionBar>
  <stackLayout orientation="horizontal">
	<image src="res://icon" width="40" height="40" verticalAlignment="center" />
	<label text="NativeScript" fontSize="24" verticalAlignment="center" />
  </stackLayout>
</actionBar>

Setting an app icon for Android

<actionBar title="My App" android.icon="res://icon" android.iconVisibility="always" />

Removing the border

By default, a border is drawn at the bottom of the <actionBar>. In addition to the border, on iOS devices a translucency filter is also applied over the <actionBar>.

To remove this styling from your app, you can set the flat property to true.

<actionBar title="My App" flat="true" />

Props

Name Type Description
title String Gets or sets the title shown in the bar.
android.icon String Gets or sets the icon to be shown on Android devices.
android.iconVisibility String Gets or sets icon visibility on Android devices.
flat boolean Removes the border on Android and the translucency on iOS. Default value is false.

Native component

Android iOS
android.widget.Toolbar UINavigationBar

ActionItem

<actionItem> is a UI component that lets you add action buttons to the <actionBar> component.

Basic use

<actionBar title="My App">
  <actionItem on:tap="{onTapShare}"
	ios.systemIcon="9" ios.position="left"
	android.systemIcon="ic_menu_share" android.position="actionBar" />
  <actionItem on:tap="onTapDelete"
	ios.systemIcon="16" ios.position="right"
	text="delete" android.position="popup" />
</actionBar>

Props

Name Type Description
ios.systemIcon Number Gets or sets the icon of the ActionItem for iOS. The value must be a number from the UIBarButtonSystemItem enumeration.
android.systemIcon String Gets or sets the icon of the ActionItem for Android. The value must be the name of a drawable resource.
ios.position String Gets or sets the position of the ActionItem within the ActionBar for iOS.
Valid values: left or right.
Default value is left.
android.position String Gets or sets the position of the ActionItem within the ActionBar for Android.
Valid values:
actionBar (places the item in the ActionBar)
popup (places the item in the options menu; renders items as text)
actionBarIfRoom (places the item in the ActionBar if there is enough room for it there; otherwise, placess it in the options menu)
Default value is actionBar.

Events

Name Description
tap Emitted when the ActionItem is tapped.

Native component

Android iOS
android.widget.Toolbar UINavigationItem

NavigationButton

<navigationButton> is a UI component that provides an abstraction for the Android navigation button and the iOS back button.

Extends <actionItem>.

<actionBar title="My App">
  <navigationButton text="Go back" android.systemIcon="ic_menu_back" on:tap="{goBack}" />
</actionBar>

Props

Name Type Description
text String (iOS-only) Sets the text of the button.
android.systemIcon String (Android-only) The icon to be shown in the button. You can specify any system icon whose name begins with the ic_ prefix. For a complete list of the available icons, see the R.drawable Android class.

Events

Name Description
tap Emitted when the <NavigationButton> is tapped.

Native component

Android iOS
android.widget.Toolbar UINavigationItem

Components

ActivityIndicator

<activityIndicator> is a UI component that shows a progress indicator signaling to the user of an operation running in the background.

<activityIndicator busy="{true}" on:busyChange="{{onBusyChanged}}" />

Props

Name Type Description
busy Boolean Gets or sets whether the indicator is active. When true, the indicator is active.

Events

Name Description
busyChange Emitted when the busy property is changed.

Native component

Android iOS
android.widget.ProgressBar UIActivityIndicatorView

Button

<button> is a UI component that displays a button which reacts to a user gesture.

For more information about the available gestures, see Gestures in the official NativeScript documentation.

<button text="Button" on:tap="{onButtonTap}" />

Props

Name Type Description
text String Sets the label of the button.
textWrap Boolean Gets or sets whether the widget wraps the text of the label. Useful for longer labels. Default value is false.

Events

Name Description
tap Emitted when the button is tapped.

Native component

Android iOS
android.widget.Button UIButton

DatePicker

<datePicker> is a UI component that lets users select a date from a pre-configured range.

<datePicker date="{someDate}" />

<datePicker> provides two-way data binding using bind.

<datePicker bind:date="{selectedDate}" />

See also: TimePicker.

Props

Name Type Description
date Date Gets or sets the complete date.
minDate Date Gets or sets the earliest possible date to select.
maxDate Date Gets or sets the latest possible date to select.
day Number Gets or sets the day.
month Number Gets or sets the month.
year Number Gets or sets the year.

Events

Name Description
dateChange Emitted when the selected date changes.

Native component

Android iOS
android.widget.DatePicker UIDatePicker

Frame

<frame> is a UI component used to display <page> elements. Every app needs at least a single <frame> element, usually set as the root element. Svelte Native creates the root frame for you.

If you need to create multiple frames, you can do so by wrapping them in a Layout, for example if you want to have 2 frames side-by-side

<gridLayout columns="*, *">
  <frame col="0"/>
  <frame col="1"/>
</gridLayout>

The first child element of a frame will become its defaultPage. This is the page shown before any navigation.

<frame>
  <page>
	<actionBar title="Default Page Title" />
	<gridLayout>
	  <label text="Default Page Content" />
	</gridLayout>
  </page>
</frame>

You can use a component as the default page for a frame, as long as it defines page as its root element.

<frame>
  <Home />
</frame>
import Home from './Home.svelte'

Native component

Android iOS
org.nativescript.widgets.ContentLayout UINavigationController

HtmlView

<htmlView> is a UI component that lets you show static HTML content.

See also: WebView.

<htmlView html="<div><h1>HtmlView</h1></div>" />

Props

Name Type Description
html String The HTML content to be shown.

Native component

Android iOS
android.widget.TextView UITextView

Image

<image> is a UI component that shows an image from an ImageSource or from a URL.

NativeScript aliases ~ to the app directory.

<image src="~/logo.png" stretch="none" />

Images can be loaded from external urls

<image src="https://svelte-native.technology/media/todoapp/todo-add-item.png" stretch="none" />

Images can also be displayed from the App_Resources folder using the res:// scheme.

<image src="res://icon" stretch="none" />

NativeScript also supports data uris that are base64 encoded

<image src="data:Image/png;base64,iVBORw..." stretch="none" />

Props

Name Type Description
src String or ImageSource Gets or sets the source of the image as a URL or an image source.
imageSource ImageSource Gets or sets the image source of the image.
tintColor Color (Style property) Sets a color to tint template images.
stretch Stretch (Style property) Gets or sets the way the image is resized to fill its allocated space.
Valid values: none, aspectFill, aspectFit, or fill.
For more information, see Stretch.
loadMode Gets or sets the loading strategy for the images on the local file system.
Valid values: sync or async.
Default value: async.
For more information, see loadMode.

Native component

Android iOS
android.widget.ImageView UIImageView

Label

<label> is a UI component that displays read-only text.

IMPORTANT: This <label> is not the same as the HTML <label>.

<label text="Label" />

Styling the label

If you need to style parts of the text, you can use a combination of a FormattedString and Span elements.

<label textWrap="{true}">
  <formattedString>
	<span text="This text has a " />
	<span text="red " style="color: red" />
	<span text="piece of text. " />
	<span text="Also, this bit is italic, " fontStyle="italic" />
	<span text="and this bit is bold." fontWeight="bold" />
  </formattedString>
</label>

Props

Name Type Description
text String Gets or sets the text of the label.
textWrap Boolean Gets or sets whether the label wraps text.
Default value: false.

Native component

Android iOS
android.widget.TextView UILabel

ListPicker

<listPicker> is a UI component that lets the user select a value from a pre-configured list.

<listPicker items="{listOfItems}" selectedIndex="0"
	on:selectedIndexChange="{selectedIndexChanged}" />

<listPicker> provides two-way data binding using v-model.

<listPicker items="{listOfItems}" v-model="selectedItem" />

Props

Name Type Description
items Array<string> Gets or sets the items displayed as options in the list picker.
selectedIndex Number Gets or sets the index of the currently selected item.

Events

Name Description
selectedIndexChange Emitted when the currently selected option (index) changes.

Native component

Android iOS
android.widget.NumberPicker UIPickerView

ListView

<listView> is a UI component that shows items in a vertically scrolling list. To set how the list shows individual items, you use the <Template> component.

<listView items="{listOfItems}" on:itemTap="{onItemTap}">
  <Template let:item>
	<!-- Shows the list item label in the default color and style. -->
	<label text="{item}" />
  </Template>
</listView>
<script>
	import { Template } from 'svelte-native/components'
	let listOfItems = ['one','two','three']
	function onItemTap(e) { console.log(e.item) }
</script>

<listView> does not loop through list items as you would expect when using a regular svelte each block. Instead <listView> only creates the necessary views to display the currently visible items on the screen, and reuses the views that are already off-screen when scrolled. This concept is called view recycling and is commonly used in mobile apps to improve performance.

You can use the itemTap event which contains the index of the tapped item and the actual item from the list.

onItemTap(event) {
  console.log(event.index)
  console.log(event.item)
}

NOTE Unlike Svelte expressions, The listView component will not update the list items if you assign the same value to lists (eg items.push('four'); list.items =items). It will update if you assign a new list reference (eg items = items.concat('four'); list.items = items)

Props

Name Type Description
items Array<any> An array of items to be shown in the <listView>.
separatorColor Color Sets the separator line color. Set to transparent to remove it.

Events

Name Description
itemTap Emitted when an item in the <listView> is tapped. To access the tapped item, use event.item.

Native component

Android iOS
android.widget.ListView UITableView

Page

<page> is a UI component that represents an application screen. NativeScript apps typically consist of one or more <page> that wrap content such as an <actionBar> and other UI widgets.

<page>
  <actionBar title="My App" />
  <gridLayout>
	<label text="My Content"/>
  </gridLayout>
</page>

Props

Name Type Description
actionBarHidden Boolean Shows or hides the <actionBar> for the page.
Default value: false.
backgroundSpanUnderStatusBar Boolean Gets or sets whether the background of the page spans under the status bar.
Default value: false.
androidStatusBarBackground Color (Android-only) Gets or sets the color of the status bar on Android devices.
enableSwipeBackNavigation Boolean (iOS-only) Gets or sets whether the page can be swiped back on iOS.
Default value: true.
statusBarStyle String Gets or sets the style of the status bar.
Valid values:
light,
dark.

Events

Name Description
navigatedFrom Emitted after the app has navigated away from the current page.
navigatedTo Emitted after the app has navigated to the current page.
navigatingFrom Emitted before the app has navigated away from the current page.
navigatingTo Emitted before the app has navigated to the current page.

Native component

Android iOS
org.nativescript.widgets.GridLayout UIViewController

Progress

<progress> is a UI component that shows a bar to indicate the progress of a task.

See also: ActivityIndicator.

<progress value="{currentProgress}" />

Props

Name Type Description
value Number Gets or sets the current value of the progress bar. Must be within the range of 0 to maxValue.
maxValue Number Gets or sets the maximum value of the progress bar.
Default value: 100.

Events

Name Description
valueChange Emitted when the value property changes.

Native Component

Android iOS
android.widget.ProgressBar (indeterminate = false) UIProgressView

ScrollView

<scrollView> is a UI component that shows a scrollable content area. Content can be scrolled vertically or horizontally.

<scrollView orientation="horizontal">
  <stackLayout orientation="horizontal">
	<label text="this" />
	<label text="text" />
	<label text="scrolls" />
	<label text="horizontally" />
	<label text="if necessary" />
  </stackLayout>
</scrollView>

Props

name type description
orientation String Gets or sets the direction in which the content can be scrolled: horizontal or vertical.
Default value: vertical.
scrollBarIndicatorVisible Boolean Specifies if the scrollbar is visible.
Default value: true.

Events

Name Description
scroll Emitted when a scroll event occurs.

Native component

Android iOS
android.view UIScrollView

SearchBar

<searchBar> is a UI component that provides a user interface for entering search queries and submitting requests to the search provider.

<searchBar hint="Search hint" text="{searchPhrase}" on:textChange="{onTextChanged}" on:submit="{onSubmit}" />

<searchBar> provides two-way data binding using v-model.

<searchBar v-model="searchQuery" />

Props

Name Type Description
hint String Gets or sets placeholder text for the input area.
text String Gets or sets the value of the search query.
textFieldBackgroundColor Color Gets or sets the background color of the input area.
textFieldHintColor Color Gets or sets the color of the placeholder text.

Events

name description
textChange Emitted when the text is changed.
submit Emitted when the search input is submitted.
clear Emitted when the current search input is cleared through the X button in the input area.

Native Component

Android iOS
android.widget.SearchView UISearchBar

SegmentedBar

<segmentedBar> is a UI bar component that displays a set of buttons for discrete selection. Can show text or images.

As opposed to <tabView>:

  • The position of <segmentedBar> is not fixed.
  • You can place and style it as needed on the page or inside additional app elements such as hamburger menus.
  • You need to handle the content shown after selection separately.
<segmentedBar>
  <segmentedBarItem title="First" />
  <segmentedBarItem title="Second" />
  <segmentedBarItem title="Third" />
</segmentedBar>
<segmentedBar items="{listOfItems}" selectedIndex="0"
	on:selectedIndexChange="{onSelectedIndexChange}" />

<segmentedBar> provides two-way data binding using v-model.

<segmentedBar items="{listOfItems}" v-model="selectedItem" />

Props

Name Type Description
items Array<segmentedBarItem> An array of items to be displayed in the segmented bar. Represents the button labels or icons of the segmented bar.
The array must be created in advance.
selectedIndex Number Gets or sets the index of the selected item.
selectedBackgroundColor Color (Style property) Gets or sets the background color of the selected item. To set the background color of the entire bar, use backgroundColor.

Events

Name Description
selectedIndexChange Emitted when the an item on the segmented bar is tapped.

Native component

Android iOS
android.widget.TabHost UISegmentedControl

Slider

<slider> is a UI component that provides a slider control for picking values within a specified numeric range.

<slider value="80" on:valueChange="{onValueChanged}" />

<slider> provides two-way data binding using v-model:

<slider v-model="value" />

Props

Name Type Description
value Number Gets or sets the currently selected value of the slider.
Default value: 0.
minValue Number Gets or sets the minimum value of the slider.
Default value: 0.
maxValue Number Gets or sets the maximum value of the slider.
Default value: 100.

Events

Name Description
valueChange Emitted when the value of the slider changes.

Native component

Android iOS
android.widget.SeekBar UISlider

Switch

<switch> is a UI component that lets users toggle between two states.

The default state is false or OFF.

<switch checked="{true}" />

<switch>provides two-way data binding using v-model.

<switch v-model="itemEnabled" />

Props

Name Type Description
checked Boolean Gets or sets the value of the switch selection.
Default value: false.

Events

Name Description
checkedChange Emitted when the switch selection changes.

Native component

Android iOS
android.widget.Switch UISwitch

TabView

<tabView> is a navigation component that shows content grouped into tabs and lets users switch between tabs.

<tabView selectedIndex="{selectedIndex}" on:selectedIndexChange="{indexChange}">
  <tabViewItem title="Tab 1">
	<label text="Content for Tab 1" />
  </tabViewItem>
  <tabViewItem title="Tab 2">
	<label text="Content for Tab 2" />
  </tabViewItem>
</tabView>
function indexChange(args) {
	let newIndex = args.value
	console.log('Current tab index: ' + newIndex)
}

NOTE: Currently, TabViewItem expects a single child element. In most cases, you might want to wrap your content in a layout.

Adding icons to tabs

<tabView selectedIndex="{selectedIndex}" iosIconRenderingMode="alwaysOriginal">
  <tabViewItem title="Tab 1" iconSource="~/images/icon.png">
	<label text="Content for Tab 1" />
  </tabViewItem>
  <tabViewItem title="Tab 2" iconSource="~/images/icon.png">
	<label text="Content for Tab 2" />
  </tabViewItem>
</tabView>

NOTE: You can use images for tab icons instead of icon fonts. For more information about how to control the size of icons, see Working with image from resource folders.

Props

Name Type Description
selectedIndex Number Gets or sets the currently selected tab. Default is 0.
tabTextColor Color (Style property) Gets or sets the text color of the tabs titles.
tabBackgroundColor Color (Style property) Gets or sets the background color of the tabs.
selectedTabTextColor Color (Style property) Gets or sets the text color of the selected tab title.
androidTabsPosition String Sets the position of the TabView in Android platform
Valid values: top or bottom.

Events

Name Description
selectedIndexChange Emits an event object containing a value property with the index of the tapped <tabViewItem>.

Native component

Android iOS
android.support.v4.view.ViewPager UITabBarController

TextField

<textField> is an input component that creates an editable single-line box.

<textField> extends TextBase and EditableTextBase which provide additional properties and events.

<textField text="{textFieldValue}" hint="Enter text..." />

<textField> provdes two-way data binding using bind.

<textField bind:text="{textFieldValue}" />

Props

Name Type Description
text String Gets or sets the value of the field.
hint String Gets or sets the placeholder text.
editable Boolean When true, indicates that the user can edit the value of the field.
maxLength Number Limits input to the spcified number of characters.
secure Boolean Hides the entered text when true. Use this property to create password input fields.
Default value: false.
keyboardType KeyboardType Shows a custom keyboard for easier text input.
Valid values: datetime, phone, number, url, or email.
returnKeyType ReturnKeyType Gets or sets the label of the return key.
Valid values: done, next, go, search, or send.
autocorrect Boolean Enables or disables autocorrect.

Events

Name Description
textChange Emitted when the text changes.
returnPress Emitted when the return key is pressed.
focus Emitted when the field is in focus.
blur Emitted when the field loses focus.

Native component

Android iOS
android.widget.EditText UITextField

TextView

<textView> is a UI component that shows an editable or a read-only multi-line text container. You can use it to let users type large text in your app or to show longer, multi-line text on the screen.

<textView> extends TextBase and EditableTextBase which provide additional properties and events.

<textView text="Multi\nLine\nText" />

<textView> provides two-way data binding using bind.

<textView bind:text="{textViewValue}" />

Displaying multi-style text

To apply multiple styles to the text in your <textView>, you can use <formattedString>

<textView editable="{false}">
  <formattedString>
	<span text="You can use text attributes such as " />
	<span text="bold, " fontWeight="Bold" />
	<span text="italic " fontStyle="Italic" />
	<span text="and " />
	<span text="underline." textDecoration="Underline" />
  </formattedString>
</textView>

Props

Name Type Description
text String Gets or sets the value of the component.
hint String Gets or sets the placeholder text when the component is editable.
editable Boolean When true, indicates that the user can edit the contents of the container.
maxLength Number Sets the maximum number of characters that can be entered in the container.
keyboardType KeyboardType Shows a custom keyboard for easier text input.
Valid values: datetime, phone, number, url, or email.
returnKeyType Gets or sets the label of the return key. Currently supported only on iOS.
Valid values: done, next, go, search, or send.
autocorrect Boolean Enables or disables autocorrect.

Events

Name Description
textChange Emitted when the text changes.
returnPress Emitted when the return key is pressed.
focus Emitted when the container is in focus.
blur Emitted when the container loses focus.

Native component

Android iOS
android.widget.EditText UITextView

TimePicker

<timePicker> is a UI component that lets users select time.

See also: DatePicker.

<timePicker hour="{selectedHour}" minute="{selectedMinute}" />

<timePicker> provides two-way data binding using bind.

<timePicker bind:time="{selectedTime}" />

Props

Name Type Description
hour Number Gets or sets the selected hour.
minute Number Gets or sets the selected minute.
time Date Gets or sets the selected time.
minHour Number Gets or sets the minimum selectable hour.
maxHour Number Gets or sets the maximum selectable hour.
minMinute Number Gets or sets the minimum selectable minute.
maxMinute Number Gets or sets the maximum selectable minute.
minuteInterval Number Gets or sets the selectable minute interval. For example: 5 or 15 minutes.
Default value: 1.

Events

Name Description
timeChange Emitted when the selected time changes.

Native component

Android iOS
android.widget.TimePicker UIDatePicker

WebView

<webView> is a UI component that lets you show web content in your app. You can pull and show content from a URL or a local HTML file, or you can render static HTML content.

See also: HtmlView.

<webView src="http://nativescript-vue.org/" />

<webView src="~/html/index.html" />

<webView src="<div><h1>Some static HTML</h1></div>" />

Props

Name Type Description
src String Gets or sets the displayed web content.
Valid values: an absolute URL, the path to a local HTML file, or static HTML.

Events

Name Description
loadStarted Emitted when the page has started loading in the <webView>.
loadFinished Emitted when the page has finished loading in the <webView>.

Native component

Android iOS
android.webkit.WebView WKWebView

Dialogs

ActionDialog

The action() method shows a list of selectable options and a cancellation button. Use it to let the user choose between options or dismiss the selection.

The method is part of the dialogs module.

Basic use

import { action } from 'tns-core-modules/ui/dialogs'

action("Your message", "Cancel button text", ["Option1", "Option2"])
  .then(result => {
	console.log(result);
  });

AlertDialog

The alert() method shows a message and an OK button. Use it to show information and notifications that do not require an action from the user.

The method is part of the dialogs module.

Basic use

import { alert } from 'tns-core-modules/ui/dialogs'

alert('Your message')
  .then(() => {
	console.log("Alert dialog closed.");
  });

Configure dialog options

alert({
  title: "Your title",
  message: "Your message",
  okButtonText: "Your OK button text"
}).then(() => {
  console.log("Alert dialog closed");
});

ConfirmDialog

The confirm() method shows a confirmation message and Cancel and OK buttons.

The method is part of the dialogs module.

Basic use


import { confirm } from 'tns-core-modules/ui/dialogs'

confirm('Your message')
  .then(result => {
	console.log(result);
  });

Configure dialog options

confirm({
  title: "Your title",
  message: "Your message",
  okButtonText: "Your OK button text",
  cancelButtonText: "Your Cancel text"
}).then(result => {
  console.log(result);
});

LoginDialog

The login() method shows a dialog where the user can provide login credentials.

The method is part of the dialogs module.

Basic use

import { login } from 'tns-core-modules/ui/dialogs'

login("Your message", "Username field value", "Password field value").then(result => {
  console.log(`Dialog result: ${result.result}, user: ${result.userName}, pwd: ${result.password}`);
});

Configure dialog options

login({
  title: "Your login title",
  message: "Your login message",
  okButtonText: "Your OK button text",
  cancelButtonText: "Your Cancel button text",
  userName: "Username field value",
  password: "Password field value"
}).then(result => {
  console.log(`Dialog result: ${result.result}, user: ${result.userName}, pwd: ${result.password}`);
});

PromptDialog

The prompt() method shows a dialog with a single-line field for user input.

The method is part of the dialogs module.

Basic use

prompt('Your message to the user', 'Suggested user input')
.then(result => {
  console.log(`Dialog result: ${result.result}, text: ${result.text}`)
})

Configure dialog options

import { prompt } from 'tns-core-modules/ui/dialogs'

prompt({
  title: "Your dialog title",
  message: "Your message",
  okButtonText: "Your OK button text",
  cancelButtonText: "Your Cancel button text",
  defaultText: "Suggested user input",
}).then(result => {
  console.log(`Dialog result: ${result.result}, text: ${result.text}`)
});

Configure input type

You can also configure the input type using inputType. You can choose between plain text (text), email-enabled input (email), and password-like hidden input (password).

inputType: inputType.text
inputType: inputType.email
inputType: inputType.password

Example

import { inputType } from 'tns-core-modules/ui/dialogs'

prompt({
  title: "Email Prompt",
  message: "Provide your email address:",
  okButtonText: "OK",
  cancelButtonText: "Cancel",
  defaultText: "name@domain.com",
  inputType: dialogs.inputType.email
}).then(result => {
  console.log(`Dialog result: ${result.result}, text: ${result.text}`)
});

TODO...

This documentation is still a work-in-progress, like Svelte Native itself. If there are particular things that are missing or could be improved, then please raise an issue on GitHub!