Native Script
Native Script
#nativescrip
t
Table of Contents
About 1
Remarks 2
Examples 2
Installation or Setup 2
macOS 2
Windows 2
Examples 6
Chapter 3: Displaying data as list (using Repeater, ListView or *ngFor for {N}+Angular-2 a 10
Remarks 10
Examples 10
Examples 15
Console 15
Timer (JavaScript) 15
Examples 17
Examples 18
Opacity 19
Translate 19
Scale 19
Rotate 20
Remarks 21
Examples 21
Chapter 8: StatusBar 24
Examples 24
Hide/show - android 24
Examples 25
Examples 27
Credits 30
About
You can share this PDF with anyone you feel could benefit from it, downloaded the latest version
from: nativescript
It is an unofficial and free nativescript ebook created for educational purposes. All the content is
extracted from Stack Overflow Documentation, which is written by many hardworking individuals at
Stack Overflow. It is neither affiliated with Stack Overflow nor official nativescript.
The content is released under Creative Commons BY-SA, and the list of contributors to each
chapter are provided in the credits section at the end of this book. Images may be copyright of
their respective owners unless otherwise specified. All trademarks and registered trademarks are
the property of their respective company owners.
Use the content presented in this book at your own risk; it is not guaranteed to be correct nor
accurate, please send your feedback and corrections to info@zzzprojects.com
https://riptutorial.com/ 1
Chapter 1: Getting started with nativescript
Remarks
Nativescript is a highly performant cross-platform mobile app runtime, which allows you to target
iOS and android (with windows in the pipeline) using web technologies (JS and html). It was
created with a number of key aims:
• Visually Performant: no UI Jank even on android you have buttery smooth fps
• Extensible: you have access to all native APIs, to create easy cross platform plugins
• Completely native UI
• Highly Integrated with Typescript and Angular 2
• Open Source, with strong corporate backing from Telerik
Examples
Installation or Setup
The following examples show the required steps to set up a Windows or OSX system and then
sign post to troubleshooting guides in case you have any trouble.
In addition, there are examples of how to set up recommended workflows, IDEs and emulators.
macOS
1. Ensure you have the most recent Node.js LTS installed. If you use Homebrew this can be
done with brew install node4-lts.
2. Open Terminal and type npm install -g nativescript. If you get an EACCES error, use sudo npm
install -g nativescript.
3. In the command prompt type ruby -e "$(curl -fsSL https://www.nativescript.org/setup/mac)"
. (This might take a while.)
4. To verify that the above has worked, type tns doctor in Terminal.
5. If there are any errors, follow up with the troubleshooting guide.
Windows
https://riptutorial.com/ 2
Using Visual Studio Code for NativeScript development
Visual Studio Code is an open-source and feature-rich code editor from Microsoft. To set it up it for
NativeScript development, open the Command Palette (F1 or +Shift+P) and type ext install
NativeScript.
Once the NativeScript extension is installed, the debugger should allow you to set breakpoints in
your code. When a device is connected or an emulator is running, you can start your app from the
Debug tab.
$ mkdir hello-world
$ cd hello-world
$ tns create hello-world --ng
$ tns platform add android #You can only add ios on an OSX machine
Then ensure you have a device connected or an emulator running (if you don't, the default
emulator should start or an error will be raised. I would recommend genymotion for android).
If you want to use the default android emulator, add the --emulator flag.
https://riptutorial.com/ 3
As of tns 2.5 livesync is now the default action for tns run <platform>, which will automatically re-
compile when you save file changes. This can dramatically improve your development time,
however, if you make changes to your plugins, you will need to recompile properly.
1-You need to connect your device to your computer via USB cable. Make sure USB debugging is
working. You can check if it shows up when running adb devices(or tns device).
4-Go to the Settings -> About phone -> Status to view the IP address of your phone.
6-If you run adb devices (or tns device) again, you should see your device.
7- Now you can use tns run android , tns livesync android commands.
https://riptutorial.com/ 4
NOTES :
1-when WiFi network changes you do not have to repeat steps 1 to 3 (these set your phone into
wifi-debug mode). You do have to connect to your phone again by executing steps 4 to 6.
2-Android phones lose the wifi-debug mode when restarting. Thus, if your battery died, you have
to start over. Otherwise, if you keep an eye on your battery and do not restart your phone, you can
live without a cable for weeks!
WARNING :
leaving the option enabled is dangerous, anyone in your network can connect to your device in
debug, even if you are in data network. Do it only when connected to a trusted Wi-Fi and
remember to disconnect it when done!
reference:
1-Norman Peitek. 2014. How to Debug Your Android App over WiFi (without Root!). [ONLINE]
Available at: https://futurestud.io/blog/how-to-debug-your-android-app-over-wifi-without-root.
[Accessed 8 August 2016].
2-usethe4ce. 2012. Run/install/debug Android applications over Wi-Fi?. [ONLINE] Available at:
http://stackoverflow.com/a/10236938/4146943. [Accessed 8 August 2016].
https://riptutorial.com/ 5
Chapter 2: Accessing native apis
Examples
Write java code in nativescript and use it directly in javascript
https://riptutorial.com/ 6
As you see they are same. so we can write java code in nativescript as we write in android studio.
We want to Add Toast to the default app of nativescript. after creating a new nativescript project
create a directory the java/org/example directory like this:
https://riptutorial.com/ 7
MyToast.java:
package org.example;
import android.widget.Toast;
import android.content.Context;
app.component.ts:
public onTap() {
this.counter--;
org.example.MyToast.showToast(application.android.context,"You pressed the
button","short");
}
}
Notes:
https://riptutorial.com/ 8
1. showToast function accepts context to pass it to Toast.makeText an we passed a context to it
in this way :application.android.context
2. typescript doesn't know what orgis, so we declared it: declare var org:any;
@Component({
selector: "my-app",
templateUrl: "app.component.html",
})
export class AppComponent {
public counter: number = 16;
public onTap() {
this.counter--;
this.showToast("You pressed the button","short");
}
for creating toast we should call Toast.makeText and it's in the android.widget.Toast package.
Toast.makeText accepts context as first argument and we can get the context in nativescript in this
way:application.android.context
https://riptutorial.com/ 9
Chapter 3: Displaying data as list (using
Repeater, ListView or *ngFor for {N}+Angular-
2 apps)
Remarks
Note: Don't use Repeater in {N}+Angular-2 applications! The *ngRepeat is
obsolete directive in Angular-2. When you need to display repeating item
patterns use either ListView or *ngFor structural directive.
Examples
Using Repeater module to display data (NativeScript Core)
page.xml
page.ts
viewModel.set("myItems", myItems);
page.bindingContext = viewModel;
}
page.xml
https://riptutorial.com/ 10
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo">
<Repeater items="{{ myItems }}">
<Repeater.itemTemplate>
<Label text="{{ title || 'Downloading...' }}" textWrap="true" class="title" />
</Repeater.itemTemplate>
</Repeater>
</Page>
page.ts
page.bindingContext = viewModel;
}
page.xml
page.ts
https://riptutorial.com/ 11
export function navigatingTo(args: EventData) {
page.bindingContext = viewModel;
}
// example how to navigate details-page & pass the tapped item context
// frameModule.topmost().navigate({
// moduleName: "./details-page",
// context: myItems.getItem(itemIndex);
// });
}
creating-listview.component.html
creating-listview.component.ts
class Country {
constructor(public name: string) { }
}
@Component({
selector: "creating-listview",
styleUrls:["./creating-listview.component.css"],
templateUrl: "./creating-listview.component.html",
changeDetection: ChangeDetectionStrategy.OnPush
})
https://riptutorial.com/ 12
public countries: Array<Country>;
constructor() {
this.countries = [];
public onItemTap(args) {
console.log("Item Tapped at cell index: " + args.index);
}
}
ngfor.component.html
<StackLayout>
<Label *ngFor="let item of items" [text]="item"></Label>
</StackLayout>
ngfor.component.ts
@Component({
selector: 'ngfor-component',
styleUrls:["./ngfor.component.css"],
templateUrl: "./ngfor.component.html",
})
constructor(){
this.items = dataItems;
}
}
page.js
var context = {
items: [
{id: 1, name: "Foo"},
{id: 2, name: "Bar"},
{id: 3, name: "Joe"}
]
}
https://riptutorial.com/ 13
exports.loaded = function(args){
var page = args.object;
page.bindingContext = context;
}
exports.showEntry = function(args){
// select the tapped entry without passing an index or anything like that
var selectedEntry = args.view.bindingContext;
console.log(selectedEntry.id + " " + selectedEntry.name);
}
page.xml
<Repeater.itemTemplate>
<Label text="{{ name }}" tap="showEntry" />
</Repeater.itemTemplate>
</Repeater>
Read Displaying data as list (using Repeater, ListView or *ngFor for {N}+Angular-2 apps) online:
https://riptutorial.com/nativescript/topic/5226/displaying-data-as-list--using-repeater--listview-or--
ngfor-for--n-plusangular-2-apps-
https://riptutorial.com/ 14
Chapter 4: Global Variables
Examples
Console
NativeScript’s global console variable lets you print values to your terminal for debugging. The
simplest usage is passing a value to the console.log() function:
console.log("hello world");
The console object has several other methods, including dump(), trace(), assert() and more.
// Asserts a boolean condition, and prints to the console if the assertion fails.
console.assert(1 === 1, "This won’t print as the condition is true");
console.assert(1 === 2, "This will print as the condition is false");
Timer (JavaScript)
NativeScript's global timer variable lets you set timeouts and intervals for asynchronous delayed
function calls.
Importing
Timeouts
Intervals
https://riptutorial.com/ 15
// clearing the interval
timer.clearInterval(intervalId);
https://riptutorial.com/ 16
Chapter 5: implement Interface
Examples
implement View.OnLayoutChangeListener in Nativescript
Add Listener:
surfaceView.addOnLayoutChangeListener(playerLayoutChangeListener);
remove Listener:
surfaceView.removeOnLayoutChangeListener(playerLayoutChangeListener);
https://riptutorial.com/ 17
Chapter 6: Implementing Animations in
Nativescript
Examples
Background Animation of StackLayout
pages/main.component.ts
@Component({
selector: "main",
template: `
<StackLayout #el>
<Button text="Apply Changes" (tap)="changeBgColor()"></Button>
</StackLayout>
`,
styleUrls: ["pages/main/main-common.css"],
})
pages/main-common.css
StackLayout{
background-color: #333;
}
pages/main.component.ts
@Component({
https://riptutorial.com/ 18
selector: "main",
template: `
<StackLayout>
<Image #img src="~/assets/images/user-shape.png"></Image>
<Button text="Apply Changes" (tap)="animateImage()"></Button>
</StackLayout>
`,
styleUrls: ["pages/main/main-common.css"],
})
You can also write your own timing function using cubicBezier.
1. Use of cubicBezier
img.animate({
translate: { x: 0, y: 120 },
duration: 2000,
curve: AnimationCurve.cubicBezier(0.1, 0.2, 0.1, 1)
});
2. Animation Properties
Opacity
img.animate({
opacity: 0,
duration: 2000
});
Translate
img.animate({
translate: { x: 120, y: 0},
duration: 2000
});
https://riptutorial.com/ 19
Scale
img.animate({
scale: { x: 1.5, y: 1.5},
duration: 2000
});
Rotate
img.animate({
rotate: 270,
duration: 2000
});
https://riptutorial.com/ 20
Chapter 7: Multithreading Model
Remarks
The new chrome v8 engine is partially ES7 compliant. So if we add "use strict"; to top of our file
(typescript do that when transpiles typescript) we have to make sure that any functions that are on
the global scope are actually assigned to the global scope. so we should use self.functionName or
global.functionName.
Examples
use Workers in angular2 service
/app/services/greeting.service.ts :
@Injectable()
export class Greeting{
private worker;
constructor(){
this.worker = new Worker('../workers /greeting.worker');
}
sayHello(message:string, answerCallback:Function){
let requestData:request =
{'type':greetingTypes.HELLO ,'message':message} ;
this.worker.postMessage(requestData);
this.worker.onmessage = (msg)=>{
let response:response = msg.data;
if(response.type == greetingTypes.HELLO){
answerCallback(response.answer)
}
}
}
sayBye(message:string, answerCallback:Function){
let requestData:request = {'type':greetingTypes.BYE ,'message':message};
this.worker.postMessage(requestData);
this.worker.onmessage = (msg)=>{
let response:response = msg.data;
if(response.type == greetingTypes.BYE)
answerCallback(response.answer)
}
}
}
https://riptutorial.com/ 21
app/services/greeting.interface.ts :
app/workers/greeting.worker.ts :
require("globals");
import {greetingTypes,request,response} from
'../services/greeting.interface';
self.onmessage = (msg)=> {
let request:request = msg.data;
let responseData:response;
if(request.type == greetingTypes.HELLO)
console.log('worker got the message: ' +
request.message);
responseData = {'type':greetingTypes.HELLO,
'answer': 'HELLO!'};
global.postMessage(responseData);
if(request.type == greetingTypes.BYE )
console.log('worker got the message: ' +request.message);
responseData = {'type':greetingTypes.BYE ,
'answer':'goodBye!'};
global.postMessage(responseData);
};
app/app.component.ts :
constructor(private greeting:Greeting){}
public tapHello() {
this.greeting.sayHello('hi',
https://riptutorial.com/ 22
(answer)=>{console.log('answer from worker : '+ answer)});
}
public tapBye() {
this.greeting.sayBye('bye',
(answer) => {console.log('answer from worker : ' + answer)});
}
app/app.component.html :
<StackLayout>
<Button text="sayBye" (tap)="tapBye()"></Button>
<Button text="sayHello" (tap) = "tapHello()"></Button>
</StackLayout>
https://riptutorial.com/ 23
Chapter 8: StatusBar
Examples
Hide/show - android
This is a statusbar that you see on top of your screen with icons of battry,clock ... .
Hide:
frame.topmost().android.activity.getWindow().
getDecorView().setSystemUiVisibility(android.view.View.SYSTEM_UI_FLAG_FULLSCREEN);
Show:
frame.topmost().android.activity.getWindow().
getDecorView().setSystemUiVisibility(android.view.View.SYSTEM_UI_FLAG_VISIBLE );
<item name="android:windowTranslucentStatus">true</item>
in the
section.
https://riptutorial.com/ 24
Chapter 9: Styling nativescript template
Examples
Adding a sample layout in your app
main.component.ts
@Component({
selector: "main",
template: `
<StackLayout>
<TextField hint="some text"></TextField>
<Button text="Click me" class="btn"></Button>
</StackLayout>
`,
styleUrls: ["pages/main/main-common.css", "pages/main/main.css"]
})
export class MainComponent { }
StackLayout {
margin: 10;
background-color: white;
}
.btn, TextField {
margin-left: 16;
margin-right: 16;
}
.btn{
background-color: #191919;
color: #fff;
}
.btn{
https://riptutorial.com/ 25
background-color: #fff;
color: #191919;
}
app.css
@import url("~/platform.css");
TextField {
color: #e1e1e1;
font-size: 12;
}
TextField {
color: #e3e3e3;
font-size: 15;
}
TextField {
padding: 4;
}
https://riptutorial.com/ 26
Chapter 10: using native widget
Examples
Using surfaceView in ng2-TNS-Android : step by step
For example you want to use surfaceView in ng2-nativescript. As we don't have surfaceView in
nativescript we should use placeholder.
<Placeholder (creatingView)="creatingView($event)"></Placeholder>
typescript doesn't know what is android and we should add platform declaration files follow this
Answer to add them.
Import OnInit:
https://riptutorial.com/ 27
}
onLoaded(element){
let mSurface = element.android;
let holder = mSurface.getHolder();
}
ATTENTION:
It's not guaranteed that android property (element.android) will be available in ngAfterViewInit so we
used loaded event instead of that.
app.component.ts:
@Component({
selector: "my-app",
templateUrl: "app.component.html",
})
export class AppComponent implements OnInit{
onLoaded(element){
let mSurface = element.android;
let holder = mSurface.getHolder();
}
https://riptutorial.com/ 28
app.component.html :
<StackLayout>
<Placeholder #surface *ngIf="init" (creatingView)="creatingView($event)"
(loaded)="onLoaded(surface)"></Placeholder>
</StackLayout>
https://riptutorial.com/ 29
Credits
S.
Chapters Contributors
No
Accessing native
2 HabibKazemi
apis
Displaying data as
list (using Repeater,
3 ListView or *ngFor Nick Iliev, Tim Hallyburton, William KLEIN
for {N}+Angular-2
apps)
Implementing
6 Animations in Madhav Poudel
Nativescript
8 StatusBar HabibKazemi
Styling nativescript
9 George Edwards, Madhav Poudel, Nick Iliev
template
https://riptutorial.com/ 30