Building Mobile Apps With Angular or Vue.js and NativeScript {N}
In this tutorial, we go over to quickly make mobile applications using NativeScript plus Angular and NativeScript plus Vue.js.
Join the DZone community and get the full member experience.
Join For FreeMore and more Java developers have been coming into contact with front-end development in recent years. For this group of developers, it is only a small step to switch to mobile app development with NativeScript. In this post, we try to clarify the possibilities of native and hybrid app development using NativeScript.
What Is NativeScript {N}?
{N} is an open source framework (under the Apache 2 license) to build native iOS and Android apps, using TypeScript and Angular. {N} is a different technology than the hybrid frameworks, such as Ionic and Phonegap. {N} is a runtime, not a web technology. Your app will not run as a mini website in a WebView and is therefore more efficient. With {N} you have direct access to all the Native APIs of your device.
TypeScript
For Java programmers, it is interesting to realize that TypeScript (TS) has many similarities to Java. TS is the best way to write {N} apps, whether combined with Angular or not. And, further, writing native code in TS for Android is quite simple, because you can take on a lot of one-to-one in the native Java code (for example: new io.java.File()
is valid in both Java and JS/TS. That is just a bit trickier in Objective-C). It is actually very fascinating to see how NativeScript manages to implement all the native constructions with pure JavaScript. From string arrays to interfaces and implementations of abstract classes.
Why NativeScript?
One of the arguments for using NativeScript {N} is the reuse of 'Skills.' That is, someone with knowledge of JavaScript/TypeScript can immediately start with {N}. {N} is written in JavaScript or TypeScript.
Reuse of code. Write Native Mobile apps for iOS and Android with a single code base and a common interface. This is not the case with Xamarin, for example, where you have to build two interfaces for iOS and Android with one common layer. It is not surprising that the slogan of {N} is: 'Write once, run everywhere.'
It is also easy to expand with the help of {N} modules (see the examples in this article) and npm modules. Actually the plug-ins from Cordova/Phonegap.
Finally, no WebViews are used, unlike with many hybrid frameworks. With JavaScript, you have direct access to the Native APIs and making NativeScript more performant.
What Is Needed for NativeScript?
In the NativeScript docs, there is a clear description of how {N} should be installed. Because this installation does not always work flawlessly, it is wise to install 'NativeScript Sidekick.'
With Sidekick, it is possible to build apps in the cloud.
If you choose to build your apps in the cloud, you can develop your apps independently of your operating system. You can, of course, even build iOS apps on a Windows machine. It is also possible to work locally with Sidekick, but for that you have to set up your own environment with iOS Xcode and the Android SDK. Sidekick still has many known issues but is already working well.
Another nice thing about {N} is Live Sync. So if you modify a rule in the code, it will be pushed directly on the phone with the cloud build and the result of the change is immediately visible.
How Does NativeScript Work With JavaScript?
The following is a simple example of JavaScript in {N}, which instantiates an Objective-C based iOS UIAlertView
control:
var myAlert = new UIAlertView();
myAlert.message = “NativeScript rocks!”;
myAlert.show();
Because web developers do not want to learn iOS and Android specific APIs, {N} offers a set of {N} modules. These modules abstract the iOS and Android details in simple JavaScript APIs.
The above UIAlertView
-based code can be rewritten with the {N} 'Dialog module':
var dialogs = require ("ui / dialogs");
dialogs.alert ({message: "NativeScript rocks!"});
This dialogs.alert()
call also provides us with the android.app.AlertDialog
for your Android app.
Although this 'dialog' example is simple, the same technique can be used for building robust apps. For this, you can use the already existing, and mature, native iOS and Android UI components.
What Can Angular Add to NativeScript?
{N} can now also be written in Angular.
If you have knowledge of Angular, it is a small step to use Angular in {N}.
The big difference with Angular is that the browser-based HTML elements such as <div> and <span> are not available in {N}. You should use {N} UI components instead.
No DOM or browser is used in {N}. {N} UIs are native UIs and therefore disconnected from the DOM. Because Angular is an agnostic framework and is disconnected from the DOM, this framework can easily be integrated with {N}. The example below deals with this. AngularJS, unlike Angular, is not suitable for {N} because this framework is linked to the DOM.
By using Angular in {N}, you have the ability to share code between your existing web application and your Native apps. Let's look at an example.
Reuse of Code Between Web and Mobile Apps
As an example, let's show a 'Grocery List' in a web application.
import {Component} from ‘@angular/core';
@Component({
selector: ‘grocery - list '
templateUrl: ‘grocerylist.template.html '
})
export class GroceryListComponent {
groceries: string[];
constructor() {
this.groceries = [‘Cheese, ‘Eggs’, 'Tomatoes', 'Tea']
}
}
Listing 1
In Listing 1, an Angular Component is defined, which fills an array of 'groceries,' via the constructor.
TypeScript is used. This is a 'typed superset' of JavaScript and is the standard for writing Angular applications.
How Does This Cmponent Work?
Via the selector associated with the Component, you can ask Angular to instantiate and render this component, where it finds a <grocery-list> tag in the HTML (see Listing 2).
….
<grocery-list></grocery-list>
….
Listing 2
In order to render the 'Grocery list,' a template has to be defined with the name: grocerylist.template.html (see Listing 3). This template is also defined under the templateUrl
of the Component.
<p>Groceries: </p>
<ul>
<li *ng-for = “let grocery of groceries">
{{grocery}}
</li>
</ul>
Listing 3
The list of 'groceries' is iterated, using Angular's ng-for
directive.
The question now is: what else do we have to program to get the above code working for your NativeScript iOS and Android apps?
The comprehensive answer is:
The component in Listing 1 remains the same. This TypeScript code can therefore be reused between the web application and mobile apps.
The only thing you need to change is the template for this component!
You must use {N} UI components instead of HTML elements in your template (see Listing 4). What is striking is that you can still use Angular's ng-for
directive for iterating through the list.
And converting a template to {N} UI components is a simple exercise, because there is a Native UI component for every HTML element. This example also shows that Angular is disconnected from the DOM, and can therefore deal with {N} UI components.
<StackLayout *ngFor = "let grocery of groceries">
<Label [text] = “grocery"></Label>
</StackLayout>
Listing 4
HTTP Module
Another example for code reuse is the following.
{N} provides support for web APIs, such as XMLHttpRequest
and fetch()
.
You can use the HTTP module within {N}. This module makes it possible to send web requests and receive web responses.
var http = require(“http”); import HTTP module
http.getJSON(‘https://api.groceries.com’)
.then(function (result)) {
…
});
Listing 5
In the diagram below, you see on the left that {N} translates the XMLHttpRequests Web API into native code for iOS and Android. Also shown, on the right side of this diagram, is the implementation of the XMLHttpRequest that is used for the web application. This is a different implementation than the NativeScript variant.
The problem here is that we can not reuse the XMLHttpRequest implementations between the web application and mobile app. There is a ''missing link'' here, namely a generic HTTP module for the web application and the mobile app.
This can be solved with Angular. Angular adds an extra abstraction layer for handling HTTP requests/responses. This is possible with the HTTP module from Angular.
We can reuse this module between the web application and the mobile app.
For example, the code to be reused will look like this in Angular:
import {Http} from ‘@angular/http’
export class GroceryListService {
constructor(private http: Http) {}
getGroceries() {
return this.http.get(`https://api.groceries.com`)
.map((res: Response) => res.json());
}
}
Listing 6
More Tools and Features
Outside the above mentioned examples, we also have other features, such as the use of plug-ins, scaffolding, and the {N} Playground. Furthermore, you can now build a {N} app with the Vue.js framework.
Plug-ins
The interesting thing about {N} is that there are many plug-ins available in the marketplace.
You do not have to build everything yourself. Think of Facebook, fingerprint/face authentication, 'text to speech,' ads with Admob, or in-app purchases. If the plug-in is not yet available, it can always be built by you.
NativeScript Playground
{N} Playground is a tool that makes it easy to build an app using a web interface within a few minutes. See https://play.nativescript.org.
In addition to the website, two apps must be installed on a device:
- NativeScript Playground
- NativeScript Preview
After scanning the QR code of the https://play.nativescript.org website using the playground app, the app will be installed on the device. With Live Sync, all changes will be immediately visible in the app. You can also drag and drop Components (Buttons, Sliders, Charts) in your template. Super cool.
Try it out. With Playground you can easily share your {N} code and issues with other developers. It is a means to quickly get started with {N} and experience its benefits. You can also build an app with NativeScript and Vue.js.
NativeScript and Vue.js
Like Angular, Vue.js is also component based. It focusses on the view layer. Vue.js integrates easily with Angular or other front-end frameworks. And, finally, is very small and compact (21 Kb).
I'll show you a simple example of how a component looks in Vue.js and NativeScript.
First, a Vue instance is created with new Vue()
. This instance contains the data or model you want to render. In this case, we want to render the message: 'Hello Vue!'
And the second step is to define a template to show the message.
const Vue = require("nativescript-vue");
new Vue({
data() {
return {
message: 'Hello Vue!',
}
},
template: `
<Page class="page">
<Label :text="message" />
</Page>
`,
}).$start();
This component will render the following on your mobile device:
Hello Vue! |
The <Page> element is the top-level/main UI element of every NativeScript+Vue.js app. All other user interface elements are nested within.
All the code in one file!
You can experiment with Vue.js and NativeScript in the NativeScript Playground.
Build Both Web and Mobile Apps From a Single Project
Reusing code is a very important challenge for development in general.
At this moment, you can generate a web application with the Angular CLI. And for {N} you use the NativeScript CLI. Before Angular 6.1, this was a problem because the CLIs give us no possibility to create one project for the web application and the native mobile application. Of course, it is possible to maintain two separate projects and to copy-paste the shared files between the two projects. This can also be solved by using the following 'seed project.' For example: https://github.com/TeamMaestro/angular-native-seed.
But with @angular/cli 6.1.0 it is now possible to build both web and mobile apps from a single project. To realize the code-sharing dream, the Angular and NativeScript teams teamed up to create nativescript-schematics. This is a schematic collection or repository for generating components in NativeScript+Angular apps using the Angular CLI. To generate a new NativeScript+Angular project, you can use ng new
with @nativescript/schemes specified as the schema collection.
Note, you may need to install @nativescript/schematics first:
npm install --global @nativescript/schematics
For starting a new web and mobile code sharing project:
ng new --collection=@nativescript/schematics my-shared-app --shared
Conclusion
In summary, {N} is a powerful framework for building native cross-platform mobile applications with Angular, Vue.js, TypeScript, or JavaScript. You have direct access to the Native platform APIs.
With NativeScript Playground you can build an app within a few minutes. And with NativeScript SideKick you can build robust apps in the cloud.
{N} works differently from hybrid frameworks such as Phonegap, but it is extremely suitable for web developers. It is more performant and easy to learn.
Opinions expressed by DZone contributors are their own.
Trending
-
Avoiding Pitfalls With Java Optional: Common Mistakes and How To Fix Them [Video]
-
Comparing Cloud Hosting vs. Self Hosting
-
Competing Consumers With Spring Boot and Hazelcast
-
Microservices With Apache Camel and Quarkus
Comments