Bare-bones NativeScript Hello World with Angular 2 and TypeScript.
Ever since learning about NativeScript’s support for Angular 2 I’ve wanted a very simple, bare-bones tutorial on how to get it up and running.
First off, I’m writing this under the assumption that you have NativeScript installed along with TypeScript and are relatively familiar with the entire process of creating and running a NativeScript app. NativeScript has great documentation and you can use their Getting Started Guide to get familiar with this process.
Assuming you have the prerequisites installed and are semi-familiar with its process, you are going to want to create a new NativeScript project with the Typescript Template with the following command.
tns create ngSample --template typescript
Then go to the applications root directory:
cd ngSample
*I like to build the project with either tns build android or tns build ios in between each of the steps to make sure everything is on the up and up.
Next, after creating our new project and going into its root directory, we will update the dependencies for the project in its package.json file to include the necessary Angular 2 packages. I’ve found these to be the minimum requirements to get a NativeScript app running with Angular 2.
Install the updated the dependencies with:
npm install
Now, go into the root app directory and delete these files:
main-view-model.ts
main-view-model.js
main-view-model.js.map
main-page.js
main-page.js.map
main-page.xml
Open up app.ts and replace its existing contents with:
This will create our application. app.ts will load the NativeScript Angular 2 bootstrapper, that will then load the Angular 2 component MainPage that we will create in the next step.
To create the component MainPage we will update the file main-page.ts contents with:
These two files are the core of the application. MainPage contains the template that the user will see with our Hello World label. At the time of writing this I haven’t been able use Angular’s templateUrl and/or styleUrls in the Component decorator for nice code separation. If you run your app in an emulator or on a device using either tns run android or tns run ios you will see the following:
And there we have it, our very first NativeScript app with Angular 2. I’ve put the source code up on my GitHub account here: https://github.com/TheOriginalJosh/ngSample. Angular 2 has a great tutorial for getting started on https://angular.io or if you have a PluralSight account John Papa also has a fantastic tutorial. Lastly if you have any questions feel free to tweet me at @_JoshSommer I will try to help you out as best I can.
I did a part two of this about adding a reusable component. You can check it out here: https://medium.com/@_JoshSommer/bare-bones-nativescript-application-part-deux-the-re-usable-component-863584e78816#.qnl47litj