Creating a Tic Tac Toe Game With NativeScript

This post is a step by step guide to create a Tic Tac Toe Game With NativeScript. I’ll assume that you’re familiar with the basic concepts of NativeScript using Angular2. If it’s not the case, I recommend you to follow the official getting started guide, which includes the setup on every platform. Note also that the source code of this tutorial can be found on GitHub at this address.

First step, creating the application:

Creating the Domain

We’re going to start by creating the core domain of the application, based on POTOs (Plain old TypeScript Objects). The basic entities we will need are:

  • The Board, containing multiple markable Squares. We will also define a size so it can dynamically rely on it for the creation of the Squares and the check of a potential win.
  • The Squares, having a State indicating what has been played (Blank, Circle or Cross). They will also contain a set of coordinates to identify their position within the Board.

The main logic within the Board Entity will be the detection and handling of a victory. Let’s start by creating the Square which will be the single unit of the Board. We’ll put it into a new directory app/domain:

Note that we’re using an enum to define the SquareState. To make things easier for importing the entities later, let’s create an index.ts file where we will define all exports for the domain directory in one place:

We’re now ready to create the Board class. The first thing we need to do is to initialise the Squares to keep track of them. We’re going to use a simple, flat Array for this (instead of a multi-dimensional one). This will make the structure simpler for the Component afterwards:

It’s important to have a visualisation of the position of each square within the array. Consider the following picture:


Basically, the array is composed of a sequence of rows, separated by an of set which is equal to the size of the board.

Before going further with the implementation of the Board, let’s add its reference to the index.ts:

Implementing the Win Detection Algorithm

Let’s think about the algorithm that will be responsible to check for a win. Essentially, we’ll need to check if a newly marked Square triggered a win, and get the winning series of Squares in return. Since we’re using an array, the indexes will be enough. Before diving into the implementation, let’s explore all the different cases of a possible win. There is a win if any row, column, or diagonal is fully composed of Squares that are all equal, and aren’t Blank. Let’s take a look back at our Board representation and identify the related patterns.

Detecting a Win in a Row

For a win to be triggered in a row, we’ll need to check the sequence where the newly marked Square belong. The following picture shows the sequence that need to be checked after having marked the Square located at 1, 1:


Did you notice the pattern? In our case, the sequence that need to be checked is the one containing Squares with x = 1, and starts at index = (size of the board). If we generalise this, we know that we need to check the sequence having a size equal to the board’s size, starting at index = (Square.xPosition * board size). We then come to the following algorithm to gather the winning Square indexes in the marked Square’s row:

As we check through the indexes, we make sure that we return undefined as soon as we come across a State that is different that the given Square’s one, since it won’t be a win anyway.

Detecting a Win in a Column

The following picture shows the indexes that need to be checked in order to have a winning column match, when the marked Square is located at 0, 2:


This time, the sequences are not contiguous, but separated from each other by a number of indexes equal to the size of the board. We can also notice that the first element of each column will be the elements between index = 0 and index = (size of the board). Starting from the previous algorithm, we come to this one to check if there is a matching win in the given Square’s column:

Detecting a Win in the Diagonal

The difference between the diagonal and the previous cases, is that there is only one possible series. If we take the same approach as before and we look at the following picture:


We notice that the Square is in the diagonal only if x = y. Then we need to check the Squares separated by (board size + 1) indexes (and staring at index = 0). In our algorithm, that means that offset will be initialised with 0, and be augmented with (board size + 1) after every increment of the loop. Let’s introduce a new function that will handle the detection logic, as it’s common to every case:

Which allows us to write the following algorithm, for the Diagonal check:

Now we can also use the new function for the two previous cases:

Detecting a Win in Anti-Diagonal

Consider the following representation for the anti-diagonal:


In this case, we’re going to perform with the check only if (x + y) = (board size – 1). The initial offset will be (board size – 1), which will also be the increment. We then come up with the following implementation:

Let’s now create a wrap-up method to call all these functions. It will have to be called every time a player marks a Square, in order to get the winning indexes:

We create an array containing the previously defined functions in order to get a potential series of winning indexes. As soon as we get some, we return the corresponding array since we don’t have to look further. Note that we using the JavaScript call function in order to provide a reference to this to the child calls.

At this point, we can extract this logic into a new class in order to keep the Board nice and small. Let’s call it WinningIndexesRetriever and create it with the following content:

The WinningIndexesRetriever needs the Board size, as well as the Squares Array to perform, so we pass them to its constructor. Before going back to the Board, let’s add the reference of the WinningIndexesRetriever to the domain/index.ts file:

Implementing the Board

Now let’s define everything else we’ll need in the Board to serve the user interface:

  • The information about the current State, to be able to know who’s playing next
  • The scores of each States, to be able to keep track of multiple games
  • a Property to indicate that there is a draw
  • And of course, the possibility to mark a Square

Let’s start with the following implementation of the Board:

After having declared the needed instance variables, we initialise them in the constructor. We also introduce a method startNewGame() which reset the _isGameWon flag, initialise the Squares array and create a new instance of WinningIndexesRetriever. This method has been set public because we want to be able to call it explicitly from the user interface as well.

Let’s now implement a property indicating if the current game’s state is a draw. To do this, we’ll have to keep track of the marks that have been done. There is a draw when the marks count is equal to the number of Squares in the Board, and the game is not won:

Let’s now implement the method to mark a Square:

The mark() method is responsible for transforming the Square state, as well as changing the Board’s current State. We also want to increment the marks count in order to notice a possible draw. Finally, we check if the game has been won by looking if we have some winning indexes after having marked the current Square. If it’s the case, we set the _isGameWon flag, and we increment the winner’s score.

Before moving on to the creation of the user interface, let’s take a minute to think about when the user marks a Square that is not Blank. In this case, we shouldn’t increment the marks count nor change the Square’s state, so let’s add a property in Square called canChangeState:

Now we can update the mark() method to check if the given Square can change its state:

Creating the User Interface

Start by downloading the pictures I’ve used to represent the Square States here.

Then, extract them them into a new folder app/img.

I took them from the following link, and are provided by Dave Gandy.

Creating the General Layout

Let’s draw a quick sketch to display how we want the interface to look like:


In addition to the Board, we would also like to have a button to restart the game, a mini scoreboard and the information about the current player (that we’ll call the “game panel”). This placeholder can also be used to show information of a win, as well as a draw.

Let’s go ahead and create the BoardComponent:

Then, declare the BoardComponent within the AppComponentModule, located in app/main.ts:

Now, we can display the BoardComponent by including its selector in app.component.html:

We are now ready to work on the user interface.

Open up app/board.component.html and put the following content:

Notice how we’re able to simply bind the Squares to the GridLayout, since we’re using an Array. We just map each Square’s y position to the corresponding StackLayout’s [col], and x position to the [row].

Then, put the associated styles in app/board.component.css:

And the output should look like this:


Creating the Board Grid

Let’s now work to make the grid actually visible. The first thing we need is the row / column specifications. We could do it statically and simply define 3 rows and 3 columns but that would be best to use the actual board’s size, to make this dynamic. To do this, let’s add a method to the BoardComponent in order to get the Board “side specification”:

With a size of 3, this will return “*, *, *” (we want every column and every row to occupy as much space as possible).

We will also display the Square placeholders using two different colors in order to create a nice grid effect. Let’s introduce a method within the BoardComponent in order to get a ‘light-square’ or ‘dark-square’ class according to a given Square position:

We can now define the two CSS styles light-square and dark-square:

We define the StackLayouts to have 100% height and width in order to occupy the whole space within the Grid. Since the Grid has a ‘star’ specification (remember the ‘*’), that means that every Square will be equal in size.

Let’s update the Board GridLayout:

This should give us the following output:


Ok, we now have a visible Board, but the Squares aren’t really squared, so let’s correct this. We will have to do this programatically within the BoardComponent, so we’ll have to extract the GridLayout from the View. Let’s add the #boardGrid identifier to the GridLayout:

To make the Board grid squared, we’re going to use the device screen dimensions. Currently, when the GridLayout is displayed, the width will occupy the whole screen width, given the ‘star’ specification. That means that we want the height to be set to the screen width as well. If we have a larger width than height though (for instance when using a tablet), we will have to do the opposite. And since the Board is not the only element occupying the device height, we need to take the total height of the other UI elements into consideration. In our case, the overflow of height would be: height of top-panel + margin of top-panel + height of game-panel + margin of game-panel = 50 + 10 + 50 + 10 = 120. Let’s go ahead and implement this:

Output on a regular phone:


On a tablet:


We’re now done for the general layout.

Marking the Squares

Let’s now work on the visual marks of the Squares. The first thing we’re going to do, is to create a Pipe that will help us transform a SquareState into the corresponding Image source path:

Then, add it to the AppComponentModule declarations list:

Let’s first use this pipe to display the current player state in the game-panel:

And add some styling:

Let’s now use the pipe to display the Squares within the Board grid:

And add some styling:

We now need to be able to call the mark() method in order to change the state of a Square. Let’s add a mark() method to the BoardComponent:

And bind it to the (tap) event of the Square layout:

Tapping on a Square in the Board grid should now change its state visually:


Animating the Squares After a Win

Now that we’re able to mark the Squares, let’s work on the detection of a win. We already have a method to retrieve potential winning indexes within the Board Squares Array. This Array is bound to a ngForOf hook that spit out the StackLayouts representing our Squares. This means that the order of indexes is conserved, and we can dynamically access each of the StackLayouts using its corresponding index in the Squares Array.

First, we’ll have to be able identify the Square StackLayouts. To do this, we’ll add a #square identifier:

Then, to retrieve each Square StackLayout identified by #square, we’ll add a @ViewChildren property within the Component, and transform it to an Array of StackLayout:

Then, we’re going to edit the mark() method to get the winning indexes from the Board. If we get some, then we animate the corresponding Squares within the squares ViewChildren property:

That should give us:

Great! let’s now add the information about the win in the game-panel.

Displaying the Game’s Information in the Game Panel

We want to replace the content of the game-panel caption “Next to play” with a one indicating that the current player just won. Let’s introduce a dynamic caption property in the BoardComponent:

And bind it to the next-to-play Label in the game-panel:

If you try out this now, you should notice a wrong behaviour though. The displayed winner is actually the one that is supposed to play next, which also get its winning count incremented. This is due to the fact that we always switch the state, even if the game has already been won.

Let’s modify the logic in the Board to prevent the current State from changing if there is a win:

Let’s now handle the case of a draw. If this happens, we only want to display the caption “Draw” within the game panel, without any State Image. We’re going to add a property to return the visibility of the next-to-play Image in the game-panel. If the Board is in a draw state, then we return ‘collapsed’, and ‘visible’ otherwise. We also modify the gamePanelCaption property to include the draw case:

Now, we can bind the Image visibility to the property we’ve just created:

Restarting the Game

Last step: bind the Restart Button with the start of a new game. Add the following method in the BoardComponent:

And bind it to the (tap) event within the Resart Button:

Bonus: Changing the Size of the Board

As you’ve noticed, we took care to make every computation according to the Board size. Try to change it to 6 to see if the algorithms still work:

Looks like it does šŸ˜‰

That’s it! If you liked this tutorial, please share it. Don’t hesitate to leave a comment for any questions or possible enhancements, I would love to hear about your feedback.

Package an Angular CLI Application into Electron


Electron is a Framework from the GitHub’s team enabling the development of cross-platform desktop application using web technologies (HTML, CSS, JavaScript…). The packaging process works pretty much out of the box, and an already up and running web application will work exactly the same way once launched in an electron application. In this post, I’ll give you some tips to integrate an Angular CLI with Electron painlessly.

So, first step, create the Angular app using the CLI:

Then, install the electron package globally:

Once that done, you will have to create two files indicating Electron how the app should be packaged. We will put them into a new electron folder located in src:

The first file, package.json, indicates the information about the electron application as well as where to find the script to start it. Let’s create it with the following content:

The second file (here, electron.js) is the script indicating how the application should behave while creating the main window, and how it should handle the different events such as when the windows are closing.

Let’s just take the one from the official quick start guide , and place it into src/electron.js:

There is also one modification to the angular code base that we need to do in order to make it run smoothly with Electron (according to this SO answer). Edit src/index.html and change:


This is necessary because Electron is using the file:// protocol instead of http://.

The last step is to add some scripts to build the app for Electron. What we need is to copy the two created file into the dist folder when building the app. Open up package.json (this time, the one at the root, not the one in src/electron) and edit the “scripts” section to add the two following scripts:

The first one is a simple ng build followed by a copy of all the files contained in src/electron/ to dist/ (created by ng build). The second one uses the build-electron script but adds the electron command to start the app using Electron, from the dist/ folder.

Go ahead, and run:

And you should see your Angular app packaged into a desktop application:


Create a Chat Interface With NativeScript


This article is a step by step guide for creating a Chat Component using Angular2 and NativeScript. You can find the complete source code on GitHub.


I’ll consider that NativeScript and its dependencies have already be set up and configured on your machine. If it’s not the case, you can follow the official guide available here.

Start by creating the app, running:

Prepare the Data

Let’s now prepare the data model. We’ll need the following:

  • the information of the current user, or ‘me’. It should have a name, and a mini profile picture that will be displayed along with each message.
  • The information of the other user, or ‘other’. Also has a profile picture but also a cover that will be displayed on top of the screen.
  • A list of messages, written either by ‘me’ or ‘other’. Each message has a content text, as well as a date.

As these data will be pretty specific to your application, we will work with fake ones. Let’s implement a ChatService that will provide us with some fake data. I’m going to use the faker library for this, so install it as a dependency first:

Let’s also add some interfaces in order to structure the data a little bit. This will improve the readability of the service and help us identify quickly what we will need for the future, real implementation:

Now we can implement our fake ChatService by making use of the previously declared Chat interface:

The goal of this service is to come up with a Chat object populated with some random data, and 4 messages. These will be distributed randomly between ‘me’ and ‘other’. Before returning the list of messages, we sort them by their date for the actual stream to make sense. Notice also the use of the image service. it enables us to retrieve images identified by the given id, and with the given size. Feel free to visit the website and choose whatever image id’s you want for your application.

And example of call from ChatService.getChat() will be:

Create the Chat Component

The main Component will be the ChatComponent, which will host the conversation interface and make use of the ChatService to populate it. Go ahead and create the it with the following content:

We have declared three instance variables to be accessible from the ChatComponent Template: me, other and messages. These are initialized with the data coming from the getChat() call.

Create the Interface

Let’s now display the data within our ChatComponent Template. For our first iteration, we’ll focus on the display of the data as-is, without any styling or images. The interface will be split into three parts:

  • the header, where the information about the other participant are displayed (photo, cover and name)
  • the chat box, where the messages bubbles are displayed
  • the message box, where the current can write and send a new message

Create the chat.component.html Template and put the following content:

Before running the application to visualize the result, we need to reference the ChatComponent selector within the AppComponent. To do this, we first need to update the corresponding Module, located in app/main.ts:

Now we can include include our selector within the AppComponent Template:

Notice that we didn’t have to reference any directive within the AppComponent, since we’re doing it at the Module level.

Now, run your application and you should see this:


This is clearly not a useful interface. Let’s now work on the styling to improve this a little bit.

Style the Interface

Let’s start with the header. We will display the other user’s cover in the background, and the profile picture and the name on top of it.
Open up chat.component.html and update it with the following content:

Then, we’ll style it using the folowing CSS:

The profile picture is rounded using a border-radius. We wrap it into a container which is also rounded and white-bordered in order to highlight it within the cover.

The result:


Let’s now work on the body of the interface, or the “chat box”. We want to instantly notice from whose sender is the message, so we’ll have to declare two sets of styles: one for ‘other’, one for ‘me’. We also want to display the sender’s profile picture beside every bubble.

We’ll start with the bubble styling. Open up the chat.component.css Stylesheet and add the following properties:

This way, we have two main bubble classes with different colors and shift positions. How are we going to differentiate them among the messages in the ListView though? We’ll first declare a new method in ChatComponent to get the bubble CSS class according to the given message:

Then, we’ll update the chat box ListView to include the styling:

This should now look like this:


This already starts to look like a chat interface, but we’re not over yet. We’ll now add the profile picture thumbnails beside each bubble. we’ll also alternate the photo position between right and left depending on the sender.

First, edit the chat box with the following content:

We’ve change the wrapping ‘bubble-container’ to a GridLayout instead of a StackLayout, in order to provide a floating layout to host the bubble aside with the sender’s picture. Then, we include the Image containing the picture below the bubble StackLayout.

It’s important to note that the images will be loaded along with every item in the ListView. In a real world application, we would probably cache them in order to improve the performance but this goes beyond the scope of this tutorial.

This brings us to the following styles:

which gives us the following result:


Let’s enhance the styling a bit, for instance by dropping this ugly line under the TextView, and reducing the size of the message-date Label:

It would also be nice if we could have a more readable date output for the messages. One way to do this is to introduce a Pipe that will format the date. We’ll use the moment library, that you can install running:

Now we can create a new Pipe and make use of moment’s .fromNow() function to return the time when the message has been sent, relatively from the current date:

We then need to declare the Pipe within the AppModule before we can use it:

And finally:

Which gives us:


Let’s now tackle the last part of the interface, which is the message box. First, some styling:

Now, we’re going to handle the logic allowing the user to send a new message.

Send a new message

The first thing we need to do is to bind the (tap) event to a sendMessage() function, which we’ll implement in the ChatComponent. When the Send button is tapped, we will want to create a new message with the content of the mesage box, as well as scrolling down to it. In a real world application, we would also have to send a request to a backend to notify the new message but that is out of the scope of this post.

Go ahead and update the code for the Send Label:

Then, we will need a reference to both the chat box ListView and the newMessage TextView in the ChatComponent:

Then, we’ll implement the actual sendMessage() method:

So the main method is sendMessage(), which collect the content of the newMessage TextView. After adding the message to the mesages array, we call scrollChatToBottom() which goes down to the last index within the array, corresponding to the recently added message. Note that we made the scroll asynchronous to make sure that we catch the right moment, where the item has been correctly set up within the ListView. Finally, we clear the text from the TextView and we focus on the chatBox in order to hide the keyboard.

There is one last thing we need to do: scroll down to the bottom of the chat when the Component is initialized. We can do this by binding the (loaded) event from the chatBox ListView to the scrollChatToBottom() method (which now has to be set to public instead of private):

And we’re now done with our Chat interface. You can now back it with your actual data model.

I hope this tutorial has been useful to you. If it’s the case, please share it and don’t hesitate to leave a comment in case of any trouble !

Create a Cross-Platform Mini Photo Gallery With NativeScript and Angular2


In this post, I’ll guide you through the creation of a mini photo gallery using NativeScript and Angular2, that you’ll be able to reuse within other components of your application. The sample will run on both iOS and Android Platforms.

Initial Setup

I’ll suppose that you already have NativeScript and all the dependencies installed. If it’s not the case, take a look at the official documentation.
When this is done, go ahead and create a new project using Angular using the NativeScript CLI:

tns create tns-photo-gallery --ng

Creation of the component

The goal here is to create a Component that you could use everywhere throughout your application. We’ll then create a dedicated component called PhotoGalleryComponent. Go ahead and create the initial skeleton for it:

// app/photo-gallery.component.ts

import { Component } from '@angular/core';

  selector: 'photo-gallery',
  templateUrl: 'photo-gallery.component.html',
  styleUrls: ['photo-gallery.component.css']
export class PhotoGalleryComponent {

Setup nativescipt-ng2-fonticon

The first thing I recommend, is using the nativescript-fonticon plugin which allows to use fonticons such as the one from FontAwesome with ease.
Start installing the package, by running:

npm install nativescript-ng2-fonticon --save

Once this done, you’re going to have to download the actual fonts and place it somewhere into your {N} project:

curl -O
unzip font-awesome-4.6.3
cp font-awesome-4.6.3/css/font-awesome.css app/
mkdir app/fonts
cp font-awesome-4.6.3/fonts/fontawesome-webfont.ttf app/fonts
rm -rf font-awesome-4.6.3*

Next, add:

.fa {
  font-family: FontAwesome, fontawesome-webfont;

To the app.css file.
Finally, edit your app/main.ts file to register the TNSFontIconService dependency:

  provide(TNSFontIconService, {
    useFactory: () => {
      return new TNSFontIconService({
        'fa': 'font-awesome.css'

Take a Photo and Display it

For our first step, we’re going to use the device camera to take a photo, and display it within a placeholder that we’ll define on our template. Let’s start with the following basic template:


      ="'fa-camera' | fonticon"
      class="fa take-picture-icon"></Label>

We display a StackLayout containing two elements: the Image that will contain the displayed picture from the camera, and a button to take the picture.
We use the “aspectFill” stretch property to make the source picture fill the Image element while keeping its aspect ratio. For more information about the available stretch properties, visit the NativeScript API reference. The default src is bound to the Component picturePlaceholderPath property, which we’ll define in a minute.
The button is composed of a StackLayout acting as a wrapper and a camera icon using a fonticon from FontAwesome. The wapper is bound to the takePicture() function that we’ll define in the Component as well.

Let’s style this a little bit:

/* app/photo-gallery.component.css* /

Image.picture-placeholder {
  height: 250;

StackLayout.take-picture-icon-wrapper {
  horizontal-align: right;
  margin: 15;
  padding: 15;
  border-width: 1;
  border-color: #CCCCCC;
  border-radius: 8;

Label.take-picture-icon {
  font-size: 25;

Since space is a rather scarce resource on a mobile, we limit the height of the displayed picture to 250 dip.

And finally, the Component itself:

// app/photo-gallery.component.ts

import {Component, ViewChild, ElementRef} from '@angular/core';
import {TNSFontIconService, TNSFontIconPipe} from 'nativescript-ng2-fonticon';
import {Image} from 'ui/image';

import {ImageSource} from 'image-source';
import * as camera from 'camera';

  selector: 'pg-photo-gallery',
  templateUrl: 'photo-gallery.component.html',
  styleUrls: ['photo-gallery.component.css'],
  pipes: [TNSFontIconPipe]
export class PhotoGalleryComponent {
  @ViewChild('displayedPicture') displayedPictureRef: ElementRef;

  constructor(private fonticon: TNSFontIconService){

  get picturePlaceholderPath(): string {
    return '~/images/placeholder-img.jpg'

  takePicture(): void {
      width: 400, height: 400, keepAspectRatio: true 
    .then((picture) => {

  display(picture: ImageSource) {
    const displayedPictureView = <Image>this.displayedPictureRef.nativeElement;
    displayedPictureView.imageSource = picture;

Few things here. First, notice the injection of the TNSFontIconService, which is necessary for the use of the TNSFontIconPipe. Then, the picturePlaceholderPath() getter that we referenced in the template. The picture used is the following:


Just download it and place it to the app/images directory.

The takePicture() function makes use of the NativeScript camera module. We call the camera.takePicture() function with a maximal resolution of 400 * 400 (dip). Finally, when we get access to the taken picture, we display it by setting it to the imageSource property of the Image identified by #displayedPicture.

To test this, just reference the Component selector into the app.component.html Template:


And the result should look like this (on Android):

Display Multiple Pictures

Let’s modify the Component to be able to display multiple photos through their thumbnails. Let’s declare an Array that will contain all the taken pictures. Each time we’ll take a picture, we want to store it in this array as well:

import {GC} from 'utils/utils';
export class PhotoGalleryComponent {
  @ViewChild('displayedPicture') displayedPictureRef: ElementRef;

  pictures: Array<ImageSource> = new Array<ImageSource>();

  constructor(private fonticon: TNSFontIconService){

  get picturePlaceholderPath(): string {
    return '~/images/placeholder-img.jpg'

  takePicture(): void {
      width: 400, height: 400, keepAspectRatio: true 
    .then((picture) => {

The GC() function is called to clean up the mess in the memory let by camera.takePicture(). Without this, the application on Android will constantly crash after some pictures, leaving us with nothing but OutOfMemory exceptions. Notice that we use the Array.unshift() function to add the pictures. It’s because we will display the pictures from left to right instead of the other way around.

Now, we want to display all the taken photos as thumbnails. Edit the template file:

    columns="*, auto" 
          *ngFor="let picture of pictures" 
        ="'fa-camera' | fonticon"
        class="fa take-picture-icon"></Label>

We now have a GridLayout to host both the thumbnail bar and the take-picture button. We want the rows to have an automatic height, but we want the first column (the one with the thumbnail bar) to occupy as much width as possible. The thumbnail bar in question is wrapped into an horizontal ScrollView. We use a *ngFor directive in an Image to loop through each picture of the pictures the array. We bind the picture to the src property of the Image, and the (tap) event to the display() function that we already have.

For the styling:

GridLayout.thumbnails-bar {
  margin-top: 10;

Image.thumbnail {
  margin-left: 10;
  margin-right: 10;

Image.thumbnail {
  height: 50;

This should now look like this:

Delete the Pictures

Now that we can take multiple pictures and display them, we would like to be able to delete them as well. Let’s add a delete button. We will display it only if we have at least one taken picture.
First, let’s wrap the #displayedPicture Image into a GridLayout, and add the delete icon:

  <GridLayout rows="auto">
        ="'fa-trash' | fonticon"
        class="fa delete-picture-icon"></Label>

The GridLayout has one row, set to an automatic height. This avoids the childs to take the whole screen when displayed.
The delete button uses also a fonticon, and has its (tap) event bound to the deleteDisplayedPicture() function. The visibility is set dynamically through the deleteButtonVisibility property of the Component.

The styling:

StackLayout.delete-picture-icon-wrapper {
  background-color: #000000;
  border-width: 1;
  border-radius: 8;
  color: #FFFFFF;
  border-color: #FFFFFF;
  margin: 15;
  vertical-align: bottom;
  horizontal-align: right;

Label.delete-picture-icon {
  margin: 7;
  font-size: 15;

Now, we’re going to implement the deleteButtonVisibility property in the Component:

  get deleteButtonVisibility(): string {
    return this.noPicturesTaken? 'collapsed': 'visible'

  private get noPicturesTaken(): boolean {
    return == 0;

This is pretty straightforward. We return ‘collapsed’ if there is no pitures in the array, ‘visible’ otherwise.

For the deleteDisplayPicture() function now, we’re going to have to do a few things. First, let’s introduce a getter to extract the Image View out of the displayedPictureRef variable:

private get displayedPictureView(): Image {
return this.displayedPictureRef.nativeElement;

And before going any further, let’s refactor the display() method to use this getter:

  display(picture: ImageSource) {
    this.displayedPictureView.imageSource = picture;

Finally, let’s implement the deleteDisplayedPicture() function:

  deleteDisplayedPicture() {
    let indexToDelete =;, 1);


You can clearly see that there’s something weird though: a deleted picture shouldn’t be displayed anymore.
Let’s correct this:

import * as imageSourceModule from 'image-source';

  deleteDisplayedPicture() {
    let pictureIndex =;, 1);
    if (this.noPicturesTaken) {
    else this.displayClosestPictureFrom(pictureIndex);

  concealPicture(): void {
    this.displayedPictureView.imageSource = 

  private displayClosestPictureFrom(pictureIndex: number): void {
    let pictureToDisplay =[pictureIndex];
    if ([pictureIndex] === undefined) {
      pictureToDisplay =[pictureIndex - 1];

After having deleted the picture from the array, we conceal the picture if the array is empty (noPictureTaken). Otherwise, we display the closest picture from the deleted index (from the left). We do this by picking the picture having the previously deleted one’s index. If the current picture is undefined, this means that we’re out of the bound of the array, in other words: we deleted the last picture. In that case, we just take the one directly to the left.

Result (with iOS this time):

Integration With Another Component

In itself, the Component is not really useful. But you can now integrate it into another component and use it, for example, to send the pictures to a backend or to process the given pictures. For this last example, we will use the PhotoGalleryComponent within the AppComponent and apply a grayscale filter on the displayed picture, to make it appear on the screen.
First, let’s make the displayedPictureView property public instead of private, so we can access it in the outer Component:

  get displayedPictureView(): Image {
    return this.displayedPictureRef.nativeElement;

Then, modify the app.component.html Template to add a button to trigger the image transformation, and a placeholder to display the result:

        ="'fa-cogs' | fonticon"
        class="fa process-picture-icon"></Label>

The app.css stylesheet now:

.fa {
  font-family: FontAwesome, fontawesome-webfont;

Image.transformed-picture {
  margin-top: 5;
  height: 250;

Label.process-picture-icon {
  font-size: 20;
  horizontal-align: center;

Now, for the transformation, we will have to dig into the native APIs. Let’s create a new file called image-processing.ts that we’ll place into app/utils:

// app/utils/image-processing.ts

import {Image} from 'ui/image';

declare const android: any;
declare const CGRectMake: any;
declare const CGColorSpaceCreateDeviceGray: any;
declare const CGBitmapInfo: any;
declare const CGImageAlphaInfo: any;
declare const CGBitmapContextCreate: any;
declare const CGBitmapContextCreateImage: any;
declare const UIImage: any;
declare const CGContextDrawImage: any;
declare const CGColorSpaceRelease: any;
declare const CGContextRelease: any;
declare const CFRelease: any;

export function transformToGrayScale(args: { source: Image, destination: Image }): void {
  const sourceImage = args.source.imageSource;
    if (args.source.ios) {
      const rect = CGRectMake(0, 0, sourceImage.width, sourceImage.height);
      const colorSpace = CGColorSpaceCreateDeviceGray();
      const context = CGBitmapContextCreate(
      const imageRef = CGBitmapContextCreateImage(context);
      const image = UIImage.imageWithCGImage(imageRef);

      args.destination.ios.image = image;
    else if ( {
      args.destination.imageSource = sourceImage;
      var colorMatrix = new;
      var colorFilter = new;;

And finally, we need to implement the transformDisplayedPictureToGrayScale() function to apply the transformToGrayScale() function we’ve just defined. The source is the displayedPictureView from the PhotoGalleryComponent and the destination is the placeholder referenced by #transformedPicture:

import {Component, ViewChild, ElementRef} from '@angular/core';
import {Image} from 'ui/image';

import {PhotoGalleryComponent} from './photo-gallery.component';
import {TNSFontIconService, TNSFontIconPipe} from 'nativescript-ng2-fonticon';

import * as imageProcessingModule from './utils/image-processing';

  selector: 'my-app',
  templateUrl: 'app.component.html',
  directives: [PhotoGalleryComponent],
  pipes: [TNSFontIconPipe]
export class AppComponent {
  @ViewChild(PhotoGalleryComponent) photoGalleryComponent: PhotoGalleryComponent;
  @ViewChild('transformedPicture') transformedPictureRef: ElementRef;

  constructor(private fonticon: TNSFontIconService) {

      source: this.photoGalleryComponent.displayedPictureView,
      destination: this.transformedPictureView

  private get transformedPictureView(): Image {
    return this.transformedPictureRef.nativeElement;

The final result on iOS looks like this:

And that’s it. You now have a reusable Component which is able to take pictures accessible for manipulation in another one.

If you found this article useful, don’t hesitate to share it or leave a comment. Please let me now if you encounter any trouble.
You can also find the whole source code on GitHub.

Vim Configuration for TypeScript and Angular2 Development

Slice 1

Some weeks ago, I’ve posted an article explaining my configuration for effective Rails development with Vim.
The goal of this article is to share the one I’m using for TypeScript / Angular2, through plugins and some customization. There is probably a lot more stuff available out there, but the following resources are what I consider a reasonable base to use Vim with these technologies.

typescript-vim, for TypeScript syntax support

The first must-have plugin is typescript-vim which provides support for syntax highlighting, indentation and also some in-Vim compilation features:

Screen Shot 2016-08-27 at 09.49.34

I use it mainly for the syntax / indenting but you can configure the plugin to display compilation errors in the QuickFix window. Add the following lines to your .vimrc:

let g:typescript_compiler_binary = 'tsc'
let g:typescript_compiler_options = ''
autocmd QuickFixCmdPost [^l]* nested cwindow
autocmd QuickFixCmdPost    l* nested lwindow

then, run :make while editing a TypeScript file to execute the tsc compiler and display errors in the QuickFix window:

Screen Shot 2016-08-27 at 10.07.35

vim-js-pretty-template, for Template Strings syntax support

Even if your Template Strings should never be bigger than 2 or 3 lines, it’s still useful to have syntax highlighting support for it. That’s exactly what vim-js-pretty-template provides.

After having installed the plugin, you can automatically load the configuration with TypeScript files, by putting the following to your .vimrc:

autocmd FileType typescript JsPreTmpl html
autocmd FileType typescript syn clear foldBraces

Screen Shot 2016-08-27 at 10.36.47

Tsuquyomi, to bring IDE-like features to Vim

Tsuqyomi is a powerful plugin that makes use of the TSServer (provided by TypeScript with its installation) behind the scenes to provide features such as auto-completion, symbols navigation and syntax / semantics errors display. The plugin depends on vimproc.vim which you have to install first.


The TypeScript completion is available through the Vim omni-completion (by default, accessed using ). You can also use YouCompleteMe to get the completion suggestions automatically triggered:

Automatic Files Import

Something you have to do quite often with TypeScript is import other files to make use of their exported interface. Tsquyomi makes this process really easy with the :TsuImport command. Just place the cursor over the symbol for which you’d like to have the corresponding file imported, and run the :TsuImport command:

Navigate to Symbols Definition

The plugin allows to navigate to Symbols by jumping to its definition. Place the cursor to the symbol you want to reach the definition and run :TsuDefinition:

In the previous example, I jumped to the definition of LoginComponent declared within the directives array. This brought me to the import statement on top of the file. I then pressed @: to repeat the command, which made the jump to the actual LoginComponent source file. Finally, I used C-T to jump back to the location I was before the move (exactly how you would do using CTags).

Show Symbol References

You can also use the plugin to display the references to a symbol in the QuickFix windows. use the :TsuReferences command:

Integration with syntastic, for in-editor syntax checking

syntastic is a syntax analyzer for Vim, displaying errors directly within the editor. You can configure it to get them as you save the file, without waiting to compile your code to be notified. The plugin uses external ‘checkers’ to delegate the syntax analysis. Tsuquyomi is one of those. Here are the configuration lines I use in my .vimrc to configure syntastic and Tsuquyomi:

set statusline+=%#warningmsg#
set statusline+=%{SyntasticStatuslineFlag()}
set statusline+=%*
let g:syntastic_check_on_open = 1
let g:syntastic_check_on_wq = 0
let g:tsuquyomi_disable_quickfix = 1
let g:syntastic_typescript_checkers = ['tsuquyomi'] 

As you can see, I’ve disabled the QuickFix window display while analyzing the syntax, as for me the combination of the markers and status line are enough. The last line is the actual checker declaration for typescript files.

auto-pairs, to automatically close wrapping elements

TypeScript is still JavaScript, which means that we have to deal with the kinda verbose syntax anyways. auto-pairs helps us automatically close open wrapping elements such as parenthesis, brackets, quotes… in a really smart way. It supports for example the automatic indentation when pressing Enter, or to jump the wrapping characters by typing them, instead of inserting them twice.

The documentation is pretty well written, take a look at it for more information regarding the use of the plugin.

angular-cli.vim, to control angular-cli in Vim

angular-cli.vim is a plugin I have written in order to be able to use the angular-cli directly within Vim. I have also added some navigation features that are similar to the vim-rails plugin from Tim Pope.
After having installed it, you can use the ng command through :Ng and use whatever arguments behind it.

The :E command allows you to edit an angular type quickly, using completion. The following types are supported:

  • Component
  • Template (HTML files)
  • Directive
  • Service
  • Pipe
  • Spec
  • Ng (every other file type: Class, Interface, Enum…)

To open up a component for example, start typing :EComponent with the component name and press tab to complete it:

You can also use the alternative V command, to open up the file in a virtual split instead:

You can use ESpec or VSpec the same way we did for the previous example, but you can also omit the argument to try to open the spec corresponding to the currently open file:

To generate a file, use the :G command:

For more information regarding the plugin, check out the github page. If you’d like to contribute, suggest a feature or report an issue, don’t hesitate to do so or to contact me.

I hope these information will help you being more productive with TypeScript and Angular, if you encounter any trouble during the installation or the use of one of the plugins, please write a comment and I’ll try to help. You can also checkout my dotfiles at this address.

Use Android APIĀ in NativeScript and Angular2 to Manipulate Images


One of the great things with NativeScript is the possibility to use standard web styling and templating tools (namely HTML and CSS) to build your cross-platform mobile application. Unfortunately, some features are not (yet) available, like for example the CSS background: linear-gradient property or filter. Fortunately though, NativeScript provides an almost full access to both iOS and Android native API, allowing to access powerful features, such as advanced image processing.
In this article, I will show you how to perform 3 image processing manipulation, using the Android API with TypeScript.

Before heading to the cases, go ahead and create a new NativeScript project using Angular2

tns create ImageProcessingApp --ng

Then, add the android platform support to the newly created application

tns platform add android

We will also need to add the package to be able to access the Android API within a TypeScript source file. Run the following command within the ImageProcessingApp directory:

npm install --save tns-platform-declarations

Then, add the following line to the reference.d.ts file

/// <reference path="./node_modules/tns-platform-declarations/tns-core-modules/android17.d.ts" />

Add a Linear Gradient Effect

This section will show you how to add a gradient background to a NativeScript View. To do this, we’re going to use the Android class GradientDrawable. Open up app.component.ts and add an AbsoluteLayout to the template, which will serve as the placeholder for the gradient background.

Notice the id we gave to the Layout. We’re going to need it in order to access it and start manipulate it via the Android API. Let’s start doing this right now:

We’ve used the ViewChild decorator around the background property, giving the id corresponding to the view we want to capture (#background). This is of type ElementRef.
Now, let’s create a new TypeScript file, hosting the function to apply a gradient background through the Android native API. We’ll place it in app/utils folder

We’e using a GradientDrawable object from the Android API. We take an array of color codes in input, transform them into an Android Color object and pass them to the GradientDrawable. The rest is pretty straightforward. And since we’re using TypeScript, we can get autocompletion suggestions straight to the objects from the library, which is really useful.

Now, we need to call this function within the app.component, with the given background View in input, and the colors we want for the gradient. Open up app.component.ts and update it like this:

We use the OnInit hook access the background View (we can’t do it within the constructor, because it would be too early as the view would not be created already). We then call the setLinearGradient function with the nativeElement of the View in input, as well as an array composed of the #FA7EFE and #9F14FC colors. The result:


Add a grayscale filter

For this effect, we’re going to use an existing image which we’ll put to the app/images folder. I’ll use the following image, so go ahead and download it:


Open up utils/background-processing.ts und add the following method:

Then, open up app.component.ts and write the following content:

The result:


Add a Blur Effect Using RenderScript

For this effect, we’re going to need a direct access to the picture we want to manipulate, and pass it to a RenderScript object. The picture I’m going to use can be downloaded here. Make sure to download the “Large” format (1356 x 2048). Then, implement the applyBlurredBackground() function, in background-processing.ts like this:

This one is slightly more complicated than the two others. The code related to the proccessing with RenderScript is actually an adapted version of the one I found on this article. You can adjust the radius constant to fit your needs, 25 is the max value (goes from 1 to 25). We need to pass two arguments: the actual image against wihch we want to apply the blur effect, and the view we want to use as a container.
Finally, we can use this function like this in app.component.ts:

Just like we did for the Gradient effect in the first section, we define an AbsoluteLayout as a template, and give it the #background id. This allows us to retrieve it as ElementRef, through the @ViewChild decorator. We use the image-source library to retrieve the background from the images folder, and then, we pass them together to the applyBlurredBackground() function, which provides the following result:


Create a Simple Calculator With NativeScript and Angular2

NativeScript is a really exiting technology, which enables the development of native mobile applications using JavaScript, as well as CSS and HTML. Everything has been thought to make the transition from web to mobile development almost seamless, and this creates the possibility to build parts of your application that are usable for the web, and both Android and iOS mobile platforms. The best part: NativeScript also uses Angular2 and all the greatness that come with it (including TypeScript). This is what we’ll be using for this tutorial, which will show you how to build a really basic calculator for mobile. Let’s get started:

Setting up NativeScript

The easiest way to perform this step is to go and visit the official setup page from NativeScript. I’m personnaly using the Genymotion emulator and I really recommend it. The tutorial will use exclusively Android but since there is nothing really platform specific, this should work for iOS as well.

Starting the ns-calculator Project

To create the application using the NativeScript cli, run:

tns create ns-calculator --ng

The –ng flag indicates that weā€™ll be using Angular2. We then need to add the platform we want to support. As already said, I’ll be using Android, which is done through the following command:

tns platform add android

If you’d like to add iOS as well:

tns platform add ios

If this worked well, you should now have the following structure in place:

the app folder is where we’ll spend all our time. For the first step, let’s open up app/app.component.ts and do some clean up in order to start from a healthy state:

import {Component} from "@angular/core";

    selector: "my-app",
    templateUrl: "app.component.xml"
export class AppComponent {

The only thing I did is to delete the content from the AppComponent class, as well as replacing app.component.html with a .xml version. Both will actually do the job, and it’s just a matter of preference.

Next, let’s create the initial layout. Open up the app/app.component.xml, and put the following content:

<GridLayout columns="*, *, *, *" rows="auto, auto, *, *, *, *, *" >
  <Label class="result" text="RESULT" colSpan="4"></Label>
  <Label text="OPERATON" row="1" colSpan="4"></Label>
  <Button row="2" col="0" text="7"></Button>
  <Button row="2" col="1" text="8"></Button>
  <Button row="2" col="2" text="9"></Button>
  <Button row="2" col="4" text="+"></Button>
  <Button row="3" col="0" text="4"></Button>
  <Button row="3" col="1" text="5"></Button>
  <Button row="3" col="2" text="6"></Button>
  <Button row="3" col="3" text="6"></Button>
  <Button row="3" col="4" text="-"></Button>
  <Button row="4" col="0" text="1"></Button>
  <Button row="4" col="1" text="2"></Button>
  <Button row="4" col="2" text="3"></Button>
  <Button row="4" col="3" text="X"></Button>
  <Button row="5" col="0" text="0"></Button>
  <Button row="5" col="1" text="."></Button>
  <Button row="5" col="2" text="("></Button>
  <Button row="5" col="3" text=")"></Button>
  <Button row="6" col="0" text="UNDO"></Button>
  <Button row="6" col="1" text="CLEAR"></Button>
  <Button row="6" col="2" colSpan="2" text="="></Button>

We’ve created a GridLayout with 4 columns and 7 rows. We indicate that all the columns should use all the space available to them (through the ‘*’ symbol). Since We set this up for all of them, they should share the space equally between them. For the rows, we did the same apart from the two first ones. We just want them to occupy only the space they need (which is their default height).

We’re going to add a little bit of CSS to style this up. Edit app/app.css with the following content:

button, label{
  horizontal-align: center;    

label {
  font-size: 36;

label.result {
  font-size: 42;
  horizontal-align: left;

button {
  font-size: 36;
  width: 100%;

The result should look like this:


This is nice, but this doesn’t do much for the moment, so let’s work on this. Edit app.component.ts with the following content:

import {Component} from "@angular/core";

    selector: "my-app",
    templateUrl: "app.component.xml"
export class AppComponent {
  operation: string = '';

  append(element: string){
    this.operation += element;

We declare an operation variable of type string. The only operation for now is append(), which takes a string in input and add it to the operation variable. We need to do two things in order to put this in use: bind the operation variable to one of the labels in our layout, and call append for every button, with the corresponding elements as parameter. Edit app.component.xml with the following content:

<GridLayout columns="*, *, *, *" rows="auto, auto, *, *, *, *, *" >
  <Label class="result" text="RESULT" colSpan="4"></Label>
  <Label text="{{ operation }}" row="1" colSpan="4"></Label>
  <Button (tap)="append('7')" row="2" col="0" text="7"></Button>
  <Button (tap)="append('8')" row="2" col="1" text="8"></Button>
  <Button (tap)="append('9')" row="2" col="2" text="9"></Button>
  <Button (tap)="append('+')" row="2" col="4" text="+"></Button>
  <Button (tap)="append('4')" row="3" col="0" text="4"></Button>
  <Button (tap)="append('5')" row="3" col="1" text="5"></Button>
  <Button (tap)="append('6')" row="3" col="2" text="6"></Button>
  <Button (tap)="append('6')" row="3" col="3" text="6"></Button>
  <Button (tap)="append('-')" row="3" col="4" text="-"></Button>
  <Button (tap)="append('1')" row="4" col="0" text="1"></Button>
  <Button (tap)="append('2')" row="4" col="1" text="2"></Button>
  <Button (tap)="append('3')" row="4" col="2" text="3"></Button>
  <Button (tap)="append('*')" row="4" col="3" text="X"></Button>
  <Button (tap)="append('0')" row="5" col="0" text="0"></Button>
  <Button (tap)="append('.')" row="5" col="1" text="."></Button>
  <Button (tap)="append('(')" row="5" col="2" text="("></Button>
  <Button (tap)="append(')')" row="5" col="3" text=")"></Button>
  <Button row="6" col="0" text="UNDO"></Button>
  <Button row="6" col="1" text="CLEAR"></Button>
  <Button row="6" col="2" colSpan="2" text="="></Button>

We’ve now bound the operation variable to the second label through string interpolation. For every Button, we’ve bound the append method to the ‘tap’ event (equivalent to ‘click’ with Angular2 for the web), and we pass the corresponding element as parameter.
You should now be able to tap the buttons and see the operation building up on the second row of the screen:

The three last buttons require more specific behaviors. Let’s implement the undo() function. What we basically want, is to delete the last element from the whole operation. Add the following function to AppComponent:

    if (this.operation != ''){
      this.operation = this.operation.slice(0, -1)

We use the JavaScript slice method on operation in order to keep everything except the last character. Now, update the app.component.xml in order to bind this function to the tap event of the corresponding button:

  <Button (tap)="undo()" row="6" col="0" text="UNDO"></Button>

You should now be able to delete the last entered element:

Next, comes the clear() function. This one is pretty straightforward, we just want to empty the operation variable:

    this.operation = '';

Alright, only one step left, which is the most important: the evaluation of the operation to get the result. Let’s introduce a new variable: result, of type string as well, which will host the result of the operation. Then, we’ll use the JavaScript eval() function on the operation variable, and stock the result in the result one:

import {Component} from "@angular/core";

    selector: "my-app",
    templateUrl: "app.component.xml"
export class AppComponent {
  operation: string = '';
  result: string= '';

  append(element: string){
    this.operation += element;

    if (this.operation != ''){
      this.operation = this.operation.slice(0, -1)

    this.operation = '';
    this.result = eval(this.operation);

Now, within app.component.xml, we need to do two things. First, bind the result to the first label. Then, attach the evaluate method to the ‘=’ button:

<GridLayout columns="*, *, *, *" rows="auto, auto, *, *, *, *, *" >
  <Label class="result" text="{{ result }}" colSpan="4"></Label>
  <Label text="{{ operation }}" row="1" colSpan="4"></Label>
  <Button (tap)="append('7')" row="2" col="0" text="7"></Button>
  <Button (tap)="append('8')" row="2" col="1" text="8"></Button>
  <Button (tap)="append('9')" row="2" col="2" text="9"></Button>
  <Button (tap)="append('+')" row="2" col="4" text="+"></Button>
  <Button (tap)="append('4')" row="3" col="0" text="4"></Button>
  <Button (tap)="append('5')" row="3" col="1" text="5"></Button>
  <Button (tap)="append('6')" row="3" col="2" text="6"></Button>
  <Button (tap)="append('6')" row="3" col="3" text="6"></Button>
  <Button (tap)="append('-')" row="3" col="4" text="-"></Button>
  <Button (tap)="append('1')" row="4" col="0" text="1"></Button>
  <Button (tap)="append('2')" row="4" col="1" text="2"></Button>
  <Button (tap)="append('3')" row="4" col="2" text="3"></Button>
  <Button (tap)="append('*')" row="4" col="3" text="X"></Button>
  <Button (tap)="append('0')" row="5" col="0" text="0"></Button>
  <Button (tap)="append('.')" row="5" col="1" text="."></Button>
  <Button (tap)="append('(')" row="5" col="2" text="("></Button>
  <Button (tap)="append(')')" row="5" col="3" text=")"></Button>
  <Button (tap)="undo()" row="6" col="0" text="UNDO"></Button>
  <Button (tap)="clear()" row="6" col="1" text="CLEAR"></Button>
  <Button (tap)="evaluate()" row="6" col="2" colSpan="2" text="="></Button>

And we should have the behavior we expects:

Now, if you try to evaluate an invalid operation, you’ll notice a crash of the application, as the eval() function throws an exception if the input is not valid JavaScript. Let’s catch the exception and alert the user saying that he tries to do an invalid operation. We’ll use NativeScript dialogs and specifically, the alert function. First, let’s import the dialogs module:

import dialogs = require("ui/dialogs");

Then, we update the evaluate method to catch the exception and display an error through dialogs.alert():

    try {
      this.result = eval(this.operation);
      dialogs.alert({title: 'Error', message: 'Cannot evaluate expression!', okButtonText: 'OK'});

I figured out this function definition as I wanted to change the default title which is ‘Alert’. I basically navigated to the definiton of the function, and noticed that this one was available:

    export function alert(options: AlertOptions): Promise<void>;

Navigating further to AlertOptions:

     * Provides options for the alert.
    export interface AlertOptions extends DialogOptions {
         * Gets or sets the OK button text.
        okButtonText?: string;

And DialogOptions:

    export interface DialogOptions extends CancelableOptions {
         * Gets or sets the dialog title.
        title?: string;

         * Gets or sets the dialog message.
        message?: string;


So I figured out the way to use alert(options: AlertOptions) without having to leave my editor: this is the power of TypeScript.

Let’s check out the error handling:

That’s it! we now have a simple mobile calculator (which should work on iOS as well).
You can checkout the code of this tutorial is available on GitHub.

Tips to Work Efficiently With Buffers in Vim

One of the things that determines your productivity in your text editor or IDE is the number of files you’re working with simultaneously. Ideally, you would have to be working with one single file at a time in order to focus your attention and limit the context switching which results in a costly loss of time and focus. But in reality, this isn’t likely to happen, since we’re not working within a single concern at a time (are you?). This implies having to go back and forth between the files, and Vim provides the possibility to handle this switching in a smart way, using buffers.

What is a buffer?

A buffer in Vim is simply a file that is loaded in memory so it can get accessed quickly. This is done automatically as soon as you open it up (typically using the :e command). You can also add a buffer associated to a file without having to edit it directly using :badd filename command.

Interact with buffers

To displays the open buffers, use the command:


You’ll get a list with the buffers as well as their corresponding data. The first column is the unique number identifying the buffer. The second is the set of attributes. In the above example, there is:

  • a buffer with the attribute #, which corresponds to the ‘alternate’ (last edited buffer). You can open it directly using :e #
  • a buffer with the attribute %a, which means that it’s displayed in the current window (%), and visible (a). This is technically possible for a buffer to be visible, but not in the current window when working with splits for example.

For more information regarding the :buffers command, consult the official documentation.

You can close one or multiple buffers using:

:bdelete buffer1 buffer2 ...

To switch between buffers you can use:


To open the next buffer in the list


To open the previous one.


will open up all the available buffers.

Another useful command is :bufdo which enables you to execute an operation on all open buffers. For example, to do a search replace through all buffers, you can execute:

:bufdo %s/search_tearm/replace_term/g | update

The update keyword at the end automatically saves the buffer if a replace actually takes place. To avoid having to do it every time I’m operating through multiple buffers, I have put:

set autowrite

in my .vimrc which takes care of saving the changes when vim automatically switch buffers.

To learn more about commands related to buffers manipulation, read the Vim FAQ on the subject.

Useful tips to work with buffers

Now, I’ll give you a few tips to work efficiently and move quickly around buffers.

buffers line with vim-airline

vim-airline is considered as a must-have plugin for Vim, as it adds up the graphics features cruelly missing from the default version. To me, the most useful feature is the bar displaying the list of open buffers. This is really useful because it makes you notice when you’re tending to have a list getting too big (which becomes a clear brake to your productivity).
To install vim-airline using Vundle, just place the following line in your .vimrc:

Plugin 'vim-airline/vim-airline'

And run :PluginInstall
vim-airline uses the Powerline patched fonts in order to display graphics elements within the terminal. The easiest way is to use this GitHub repository.
Clone it using:

git clone

Then switch to the created repository and run the install script:


The next step is to configure your terminal to use one of the installed fonts (ending with for Powerline). Just be aware that all the fonts won’t necessarily work well with your airline configuration and you might notice graphic bugs. But there will be a few of them that’ll do the job properly though. The one I use is called Liberation Mono for Powerline (I’m using Ubuntu).


I won’t go into the features of vim-airline because it’s not the topic of this article but I’ll share the (basic) configuration I’ve set for it within my .vimrc:

let g:airline#extensions#tabline#enabled = 1
let g:airline_powerline_fonts = 1
let g:airline_theme='powerlineish'
let g:airline#extensions#syntastic#enabled = 1
set laststatus=2

The first parameter is what I’m talking about when I say the line displaying the list of open buffers. The second is here to make airline work with the Powerline patched fonts which is mandatory to have the graphics displayed properly. Then, we set the theme, the Syntastic integration and finally we use the status bar everywhere (displayed only when you open a split otherwise).

Now, start Vim and open up a bunch of files sequentially. You’ll have the associated buffers displayed in the top bar, and have the currently open one highlighted:

Swap and close buffers quickly

Here are mappings that I use quite often:

:nnoremap <Tab> :bnext<CR>
:nnoremap <S-Tab> :bprevious<CR>
:nnoremap <C-X> :bdelete<CR>

They allow you to switch buffers: Tab for the next one, Shift-Tab for the previous one. To quickly close a buffer, I use Ctrl-X. The cool thing is that you can actually see what happens with the vim-airline buffer line:

Fuzzy Search within Buffers with ctrlp.vim

ctrlp.vim is a Vim plugin providing fuzzy finding features for files, MRU (Most Recently Used files), and Buffers. Install it with Vundle:

Plugin 'ctrlpvim/ctrlp.vim'

To open the list of buffers and start searching through it, use:


I’ve decided to map this command to Leader-B:

nmap <Leader>b :CtrlPBuffer<CR>

Now press Leader-B and start fuzzy navigating through the open buffers:

The alternate buffer is always the one selected by default, so to come back to it, just press Leader-B + Enter and there you are.

That’s it ! for any trouble / advice, please go ahead and write a comment.

You can checkout my dotfiles here.

My Vim Configuration for Rails Development


Vim is the editor of choice for many rails developers (including me). One of the reasons is the almost infinite level of configuration and customization it provides, as well as the massive choice of already existing plugins from the community. In this article, I’ll share my configuration which is really rails oriented, although there are some general tips you can use for something else.

Tmux and dispatch.vim

I’ve recently written an article to show the benefits of using Tmux and Time Pope’s dispatch.vim for quick and effective testing feedback. But you can actually achieve much more and we’ll see some example of integrations that are natively supported later in the article.
To install Tmux using Mac OS X:

brew install tmux

Using Debian / Ubuntu

sudo apt-get install tmux

You can install the dispatch plugin using Vundle:

Plugin 'tpope/vim-dispatch'

Rails Integration With vim-rails

If you had to choose only one vim plugin for Rails development, it would definitely be this one. It provides features such as inter (Rails) resources navigation, improved syntax highlighting, built-in Rake / Rails commands within Vim.
To make all this wonder available, just install it using Vundle:

Plugin 'tpope/vim-rails'

Resources Navigation

The navigation has been made easy yet extremely powerful. You just have to use the command with the following pattern :Eresource_type resource_name
For instance, opening up the UsersController file would simply be:

Econtroller users

To open the User model:

Emodel user

Without any parameter, the :Eresource will try to open up the resource linked to the one currently open one. For instance, if you have user.rb open, Econtroller will open up the associated users_controller.rb

E is actually using the Vim :e command under the hood. You can also use the alternatives like S (for :split), V (:vsplit) or T (:tabedit). If you’d like to open a controller in a new vertical split, you could do:

Vcontroller users

There are a lot of resources supported by the navigation mechanism, but here are the one I use the most often:


Navigate to Alternate File

Another helpful command is the :A (for Alternate) which takes you to the corresponding spec (or test) file. the plugin will first look for a MiniTest file if it exists, and then a spec file otherwise, so make sure that you don’t use generators automatically creating MiniTest files if you use RSpec instead. the :A command is compatible with the previously mentioned modes as well (S, V, T…).
For instance, opening the spec corresponding to the currently opened file in a new vertical split is done by calling :AV (mode placed at the end)

Navigate to Related File

We sometimes have to jump to file that is closely related to the one we’re currently editing. The command for this is :R (again, works with the S, V and T). The related files mappings are the following:

  • Model -> Schema definition
  • Controller -> View
  • Migration -> Next Migration (Previous Migration accessible using :A)

Jump to a File

the vim gf command is originally used to jump to the file described under the cursor. rails-vim extends this behavior by allowing to edit the file corresponding to the resource pointed by the cursor.

This works with multiple resources: Class / Module names, Active Record associations, layouts, stylesheets…

I usually work with vertical splits so I’ve used the key binding from this page to be able to open the file under the cursor to a new vertical split:

:map <F8> :vertical wincmd f<CR>

Command Line Integration

rails-vim enables the integration of rails and rake commands directly within Vim. The rails and rake commands are respectively accessible via :Rails and :Rake.
You can use them as you would normally do, but there are also some additional uses available. For instance, :Rgenerate model <model> will call the normal rails generate model user, and open the corresponding migration at the end of the process. :Rgenerate controller <model> will run the process and open the newly created controller:

You can also integrate with rails server using the :Rserver command. Now, if you have followed my advice, you probably have installed Tmux and the Dispatch.vim plugin. After having run a Tmux session with Vim, try to run :Rserver:

Instead of running the rails server in background as the :Rserver command normally does, it creates a new Tmux windows and run the command in it. You can now restart the server by running :Rserver! or kill it using :Rserver!- (or simply switch to the corresponding Tmux window and press Ctrl-C).

Concern and Partial Extraction

Concern and Partial extraction are made possible through the :Rextract command.
If the current opened file is a model, the result will be a concern extraction. For example, if I have the user model open and I want to select three methods for extraction. I can just go into visual mode, highlight the methods and run:

:'<,'>Rextract <concern_name>

This works with line numbers as well:

:9,19Rextract <concern_name>

The extracted methods will be put in a new file placed in app/models/concerns and inherits from ActiveSupport::Concern

The same mechanism applies for Partial extraction. Run:

:'<,'>Rextract <partial_name>; 

on the selected lines of one of your views and it will automatically create the partial with the _ prefix and replace the lines with the partial reference:

Fuzzy Finding With ctrlp.vim

ctrlp.vim is one of my favorite multi-purpose plugins for Vim. It enables to search through a directory of light using a fuzzy logic (and more). Start by installing it using Vundle:

Plugin 'ctrlpvim/ctrlp.vim'

Then go ahead and use it executing Vim in any directory and pressing Ctrl-P. You can then just type whatever you’re looking for in a fuzzy manner and press Enter to open up the found file (Ctrl-V to open in a new vertical split, Ctrl-T in a new tab):

You can also mark multiple files to open by cycling around using Ctrl-K (up) and Ctrl-J (down), then Ctrl-Z (mark file) and finally Ctrl-O to open:

You can also cycle through the available Search modes (File by default) to MRU (Most Recent Used) or opened Buffers by pressing Ctrl-F and Ctrl-B:

There is also a feature I find particularly useful: the file creation. Open up ctrlp, type the file you want to create and then press Ctrl-Y:

Why not simply use the :e command? well, this method will also create the corresponding folders if they don’t exist, which prevents you from having to manually create them before writing the new file.

The main downside with ctrlp.vim is to have to manually refresh the cache when something changes withing your current project structure (file renamed, deleted or added). you can do this by pressing F5 while ctrlp.vim open. But fortunately, there is a way around this which we’ll see later in the article.

Find Your Way in Your Source Code With CTags

Moving quickly between the references of your Rails project becomes a must when its size reaches a certain point. CTags enables you to do just that, by creating tags indexing the references of your project, in order to be reached wherever you are. You can read the following article which gives a good overview of the possibilities of using CTags with Rails.
Go ahead and generate the tags of your Rails project by running the following command, at the root:

ctags -R --languages=ruby --exclude=.git --exclude=log .

Or if you want to tag the external bundle dependencies as well (extremely useful):

ctags -R --languages=ruby --exclude=.git --exclude=log . $(bundle list --paths)

One of the common use cases is to reach a method definition while pointing at one of its calls. Point the cursor to the method for which you’d like to know the definition, and press Ctrl-] to jump to it:

Going back to your previous location is as easy as pressing Ctrl-T.
You can also do exactly the same by entering the method name instead of having to point to it by using the command:

:ta method_name

Blazing Fast Searching With the Silver Searcher

The Silver Searcher or is a searching tool which started as a clone of ack. Its creator claims a speed improvement of 5 to 10 times. Making it the default grepping command of Vim will make your search operations executed with the speed of light.
First of all, install it using:

brew install the_silver_searcher

For Mac OS X

sudo apt-get install silversearcher-ag

For Debian / Ubuntu.
Note: I had to compile from the sources in order to get the latest version of ag on Ubuntu. You might have to do this if you notice that your .gitignore is not respected while using the command.

Then, do as it’s suggested in this article from Thoughtbot and write the following lines into your .vimrc:

" The Silver Searcher
if executable('ag')
  " Use ag over grep
  set grepprg=ag\ --nogroup\ --nocolor

  " Use ag in CtrlP for listing files. Lightning fast and respects .gitignore
  let g:ctrlp_user_command = 'ag %s -l --nocolor -g ""'

  " ag is fast enough that CtrlP doesn't need to cache
  let g:ctrlp_use_caching = 0

This sets ag as the default grep command, as well as the ctrlp.vim files listing one. The speed provided by ag allows us to disable the cache, which solves the F5 problem we mentioned previously !

Then, you can map the :Ag command for instance to the \ key:

nnoremap \ :Ag<SPACE>

Using it with the text you want to search within your current project’s directory will display the result in the Vim Quickfix window. You can then press Enter on the row you want to open the corresponding file:

You can also pass an argument, like the folder in which you want to search:

:Ag app/controllers

Global Replace With qfdo.vim

qfdo.vim is a simple Vim plugin allowing to run a command for each line within the Quickfix window. Mixed with the :Ag command, it allows you to perform a two step global search replace.
Go ahead and install the plugin using Vundle:

Plugin 'karlbright/qfdo.vim'

Then write the following line to your .vimrc, which allows to auto save buffers after being automatically switched (needed for the replace withing multiple files which has to open and close multiple buffers sequentially):

set autowrite

Now suppose you want to change a method name. You can just search it using the :Ag command (through the \ key we previously mapped), then run:

:Qfdo s/method_to_search/method_to_replace_with/gce

With using the gce suffix, you’ll be prompted each time in order to confirm or reject the change. You could also replace all at one time using simply g. In action:

Syntax analysis with Syntastic and RuboCop

Syntastic is a plugin enabling the check the syntax of your source files. It displays potential warning as well as errors directly in the Vim interface and where it’s actually detected. The default checker for Ruby is RuboCop and we’ll see how to integrate it with Syntastic. First, install syntastic using Vundle:

Plugin 'scrooloose/syntastic'

Then, write the following configuration in your .vimrc:

set statusline+=%#warningmsg#
set statusline+=%{SyntasticStatuslineFlag()}
set statusline+=%*
let g:syntastic_check_on_open = 1
let g:syntastic_check_on_wq = 0
let g:syntastic_ruby_checkers = ['rubocop']

I use a minimal configuration to automatically check the syntax on open and omit on close. I also set the ruby checker to RuboCop which you can install either using:

gem install rubocop

Or by referencing the gem within your Gemfile:

gem 'rubocop', require: false

Now, you can start writing and get noticed from syntax warning and error as you save your buffers:

There is another cool trick that turns out to be really useful to do some refactoring. Go ahead and install the vim-rubocop plugin:

Plugin 'ngmy/vim-rubocop'

It enables you to use the RuboCop command directly in vim using :RuboCop. using it with the –auto-correct flag This can correct automatically some content marked as warning, use the best practices of the Ruby community instead and display the results within the QF window. Since I’m using I quite often, have mapped it to the Ctrl-A key. In action:

vim-rspec and Asynchronous Specs Run

I’ve already described this workflow in this article. It basically uses the combination of Tmux, Dispatch.vim and vim-rspec to run the specs asynchronously, and display the errors if some in the QF window. Install vim-rspec using Vundle:

Plugin 'thoughtbot/vim-rspec'

Configure the key mappings to run the appropriate specs:

map <Leader>t :call RunCurrentSpecFile()<CR>
map <Leader>s :call RunNearestSpec()<CR>
map <Leader>l :call RunLastSpec()<CR>
map <Leader>a :call RunAllSpecs()<CR>

Then, configure vim-rspec to start the rspec command using Dispatch:

let g:rspec_command = "Dispatch rspec {spec}"

When there are errors after the spec execution, the output is displayed within the QF Window. There is another plugin I use to toggle the QF maximization called vim-maximizer. It enables you to maximize / minimize the current focused window by pressing F3.
Installation with Vundle:

Plugin 'szw/vim-maximizer'

I also use the following mapping to be able to interact quickly with resulted errors:

map <F2> :Copen

To open the QF (or focus it if already open)

map , :ccl

To close it.

Since you’re still in Vim while looking at the error, you can use the usual workflow to move around and for instance copy an error message to the clipboard.


vim-surround is another multi-purpose plugin that can’t miss from your .vimrc. It enables you to work with surrounding elements (parenthesis, quotes, tags…). You can either add one, change it or delete it. It’s also compatible with the usual Vim motions (i for inside, a for around, w for word…).

Surround a word using ysiw and then the surrounding character you want, for instance ysiw' (add surrounding character ' in word):

You can also change the surround to another character, like " with csi' (change surround inside '):

It also works in visual mode. Just select the text you want to surround, and then press S. The following example uses first a tag, and then the character ' for the final output:

Installation with Vundle:

Plugin 'tpope/vim-surround'


Simple yet very handy plugin to automatically close blocks as you open them (def, if, do …). There is not much more to say about it apart that it saves a lot of time:

Installation with Vundle:

Plugin 'tpope/vim-endwise'

Git Integration with fugitive.vim

fugitive.vim is another great plugin from Tim Pope allowing you to use Git without making even a step out of Vim. You can basically use git as you would normally do using the :Git command but there’s obviously more.
Use for example :Gstatus to manage the staging area. You can select one (or many using visual mode) to commit and then press the - key. With :Gcommit, you can then write the commit message (by entering the edit mode) and save the buffer to execute your commit. Then, you can push using :Gpush. If you use the Tmux and Dispatch workflow, the push output will be displayed in a Tmux pane instead of blocking the window. In action:

Another great example is the use of :Gblame. Executing the command will open a vertical split with the output of a normal git blame. You can then select one row and press o to display the result into a split:

To execute git checkout on the current file, run :Gread:

For more detailed use cases, I suggest the following Vim Cast.

To install it using Vundle:

Plugin 'tpope/vim-fugitive'

Final Words

This is not the entire description of the configuration I use for Vim, but definitely the plugins I use the most often for my Rails development workflow. I hope you’ll be able to benefit from the tips and if you have anything useful to share or find a potential weakness / enhancements, please write a comment!
My dotfiles (Tmux, Vim) are available here.

Configure CORS to Allow Cross-Domain Requests in a Rails 5 API Application

If you have already tried to integrate a JavaScript Single Page Application with an API sitting in another domain, you’ve probably encountered blocked requests (and some frustration). This typically happens because most of the browsers don’t allow cross-domain HTTP requests originated from scripts, for security reasons. This is typically the case of the AJAX requests (XMLHttpRequests) sent by your JavaScript application.
Fortunately, there is a way to allow these requests, using the CORS mechanism.
A Rails 5 application created with the –api flag comes shipped with the rack-cors gem which provides full support for CORS. After your app creation, you’ll notice the file: config/initilizers/cors.rb which is commented out by default:

# Be sure to restart your server when you modify this file.

# Avoid CORS issues when API is called from the frontend app.
# Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin AJAX requests.

# Read more:

# Rails.application.config.middleware.insert_before 0, Rack::Cors do
#   allow do
#     origins ''
#     resource '*',
#       headers: :any,
#       methods: [:get, :post, :put, :patch, :delete, :options, :head]
#   end
# end

The only thing to do is to uncomment the lines corresponding to the actual configuration and adapt it to your needs. One example would be:

# Be sure to restart your server when you modify this file.

# Avoid CORS issues when API is called from the frontend app.
# Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin AJAX requests.

# Read more:

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins ''

    resource '*',
             headers: :any,
             methods: [:get, :post, :put, :patch, :delete, :options, :head],
             expose: ['access-token', 'expiry', 'token-type', 'uid', 'client'],
             max_age: 0

The ‘*’ symbol means no restriction. We could have also used origins '*' to allow requests coming from anywhere but this is highly unrecommended. We also added an option to expose some header values. In this example, we want to allow the usual headers needed for a token-based authentication.

And that’s basically everything you need to do to make CORS working with your Rails API. For more information on the subject, I recommend reading this article.