Angular 4 Directives Overview

WRITTEN BY GARETH DUNNE @JSDIARIES

If you missed our last Angular post please check it out here.

Not much has changed in terms of directives for Angular 4 so this post will be a general directive overview mentioning Angular 4 directive changes where appropriate.

Under the hood, a directive in Angular is just a plain JavaScript class that is decorated with the @directive decorator. In Angular, we have 3 different types of directives.

These are:

  • Component Directives
  • Structural Directives
  • Attribute Directives

An attribute directive tends to change the look and behavior of an element. Whereas a structural directive will manipulate the DOM and add or remove elements depending on what action the structural directives apply.

A Component Directive uses the shadow DOM to create encapsulated visual behavior that is typically used to create UI widgets.

Some directives go beyond the scope of this post but be sure to check out this awesome Angular + Typescript book by Yakov Fain for additional information.

Attribute Directives

We will start with attribute directives and how this interacts with our DOM and data.

We can also differentiate a component from a directive using this handy table provided for here.

You can create your own attribute directives or you can use Angular’s built in directives.

https://angular.io/docs/ts/latest/guide/attribute-directives.html

ngClass

A fairly simple illustration of a basic attribute directive, ngClass is added into our component element and its value is given as a class.


As you can see, we can use the ngClass attribute to assign a class based on styles that we had specified in our styles array.

ngFor

In short, ngFor is a directive that outputs an array element, iterating through each element inside it.

For multiple classes, we can create an array and put those classes inside it to apply to our iterative list. We can then combine this with the aforementioned *ngFor.

The let key is part of the Angular template syntax. It creates a local variable that can be referenced anywhere in that specific template. let also creates the index i and keeps it as a reference to the current whiskey. All this is done under the hood of this directive.

What if we wanted to style the first and last item in our ngFor directive? This is actually made relatively easy by using let again to assign the first items to variable first and last to variable last.

To be as efficient as possible, ngFor will attempt to not remove and recreate these DOM elements and instead to reuse and recycle when possible. This helps with performance and prevents significant slowdown in our DOM.

ngSwitch

ngSwitch provides us with a structural directive similar to a switch loops in JavaScript and our other Object Oriented language counterparts.

Here is a simple example that combines input button events with ourSwitchCase loop. Based on the number that value returns which is changed depending on which button is clicked, one of the divs with the *ngSwitchCase will be displayed.

ngIf

NgIf adds or removes an element or elements from a sub tree based on the condition specified.

If the expression assigned to ngIf evaluates to a falsy value then the element is removed from the DOM, otherwise a clone of the element is reinserted into the DOM.

This would be similar to how the display: none property behaves in CSS.

The NgModel directive allows us to provide two way data binding to our HTML element. Whatever we type in the input field will reflect in our name element. In our sample Plunker we had to import and declare our FormsModule in order for this to work. The name attribute should also have the same value as our ngModel.

Creating our own Attribute Directive

I will be going over the fantastic introduction to creating our own directives from Angular University.

We can also create our own custom directives in Angular. In this case, this directive can be applied to any HTML element on the page and will hide this element when it is clicked.

Firstly, we need to import our Angular Directives from Angular core library into your component file.

We then need to then initialise our directive meta data decorator with the selector property of our choice. In this example its HideElement.

We then want specify the CSS classes that we want to use for the fade out transition.

And we also need an action to occur when the element is clicked so we will create a function called toggle.

We than want to use a click event that will trigger the function “Toggle” that will add or remove this fade out css class but we will not be using Angular’s (click) event so how exactly will we accomplish this?

Well, we will use the Angular directive HostListener from Angular Core. Using a Host Listener, Angular will invoke the decorated method (in this case toggle) when the our html element emits the event (when clicked).

In order to access and change properties of the Host Element we must use the HostBinding Decorator. This will check the host binding properties once a change is detected.

For a more detailed explanation of creating your own Angular directives check out this tutorial from Rangle.

If this helped you out be sure to check out our resources page for more recommended reading material on Angular.

Ionic 2 – Geolocation & Google Maps

 WRITTEN BY GARETH DUNNE @JSDIARIES

Using Ionic Native

One of the most straightforward ways to demonstrate Ionic Native and how it works is to use the GeoLocation native plugin. This will allow us to use a range of methods that will configure the the users current GeoLocation and we can then use this information in combination with a Google Maps implementation as well.

There is already some well established tutorials for achieving this so I’m going reference them in this post whilst also giving an overview for those that don’t have to time to implement their own example.

Please also keep in mind this excellent Ionic 2 book that will get you up to scratch very quickly.

And these articles by Toptal might help you to further understand Ionic concepts:

Geolocation

With your Ionic 2 project already created we need to install the cordova geolocation plugin here.

This plugin will provide information about the current users device’s location, such as latitude and longitude. When starting the application, the user will receive a dialog asking for permission to use the current location.

This is a standard practice as some of the native plugins want to ensure that the user is content with sharing certain information with our Ionic 2 application.

In our created Ionic page, where we want to display our Google maps instance, we need to import our GeoLocation plugin from ionic native so we have access to it in the page.

We should then add an event click listener to the desired button that will provide the action of locating the users current position.

We are just invoking the .getCurrentPosition() method on the imported Geolocation object. Afterwards or .then(),  we assign the current value of our location variable to our components location variable of type any that was declared earlier in the component.

In our html file we are now able to output a value for our coordinates by accessing the properties for coordinates (.coords) and for the latitude value of those coordinates (.latitude) as well as the longitude (.longitude) on the location object.

Google Maps

While getting a GeoLocation is handy to know, what exactly should we do with the users position? Well you could implement the retrieved coordinates into a Google Maps implementation in your App.

There are two main ways to do this.

The first is to install Angular Google Maps. This is very well covered in the video tutorial below by Mindspace.

Fast forward to about 21:37.

And if you have the time,  be sure to watch part 1 and 2 in its entirety as you will come away with a full application with some nice Ionic Native functionality.

The second option that we can do is to use the JavaScript SDK, so that we can put in the header of our index.html file. This would be considered an easier way to implement it and it will also work in the browser as well as natively on devices .

However, for both cases you might as well generate an API key as if you were to ever to implement your app into a production environment or upload it to the app store there is a usage limit Google has and you might have to pay in order to remove the limit.

index.html Google Maps JavaScript SDK implementation
index.html Google Maps JavaScript SDK implementation

https://developers.google.com/maps/documentation/javascript/get-api-key

Without generating an API key, to use the Maps SDK simply put the following in your index.html file.

We then just need to reference the map id in our template HTML.

By default, the div containing our Google Maps object has no styling properties. We need to change this order for the map to display properly.

 

Finishing up

Overall, I hope that this post has given a good indication of how to use Ionic Native plugins and from that point how to combine them together.

I didn’t want to provide too much detail as there is already quite a lot of fully fledged tutorials on this.

However, if you followed the links and references in the tutorial provided there is plenty of information to digest but bear in mind that the way you implement Ionic Native functionality never really changes, its just the built in methods and functions of the particular Ionic Native plugin that you are using that will be different.

I’m far from an expert in Ionic 2 but as I’m getting to grips it, I’m becoming more comfortable with Hybrid App development and want to share what I’m learning so be sure to check out our future posts on it.

I’m thinking about covering the changes in Ionic 3 and what it means for the framework.

Please check out our resources here for additional reading content.

References

A lot of this post stems from Josh Morony’s Ionic Google Maps & Geolocation guide so be sure to check his post out and his great Ionic 2 content in general.

Ionic 2: How to Use Google Maps & Geolocation

Visual Studio Code Features Part 1

WRITTEN BY GARETH DUNNE @JSDIARIES

Visual Studio Code

In the last year Visual Studio Code has been constantly improving and its becoming more renown in the software development community. Coming from someone who originally used Sublime I now only use Visual Studio Code ,this is mainly because of a more diverse implementation of its own Intellisense features for languages such as TypeScript (which is is also what Visual Studio Code is written in) .

By pressing Ctrl+Space we are able to we access a huge list of member accessors/methods that you would otherwise not be aware of or that you might have to look up.

Intellisense Visual Studio
Visual Studio Code Intellisense

This saves you time and shows you description/explanation of the parameters or method accessers without disengaging you from your work environment. Some Intellisense features are not included in Visual Studio by default.

Although Visual Studio Code supports most languages out of the box you can usually find your desired language by searching for it in the extensions tab and then finding the support link on their detail page.

In comparison to other text editors such as Sublime, Brackets and Atom, Visual Studio Code has brought some core functionality from its full IDE counterpart. It brings much of this useful functionality and removes some of the more obscure features that would go unused by most day to day developers.

It is also available on Mac and Linux so non Windows users are now able incorporate a stripped down version of Visual Studio in their operating system. Lets run through some of these features included in the most recent version as of the publishing date of this post. The Microsoft devs are also kind enough to give us new monthly versions of Visual Studio Code with new features every month or so.


Syntax and Appearance

If you are looking for a font with a bit more pop in Visual Studio Code you could do worse than:

https://github.com/tonsky/FiraCode#terminal-support.

fira-code symbols
fira-code symbols

 

This add on gives your dev environment some pretty nice icons and symbols which enable your attractive code to be more attractive. It’s a winwin situation.

On a more serious note this may in fact actually increase your productivity, if your eyes are scanning across a code base, symbols and operators might stand out as more defined if they are in contrast to everything else beside it so this one is definitely worth a shot. On a more personal note I prefer the default VSC syntax highlighting over other editors such as Sublime.

I just think that every function, parameter, data annotation, keywords etc are suitably highlighted with an appropriate color, especially the dark theme. In contrast to this I thought the sublime color schemes were quite bright, neon and flashy although I was a big fan of the material design theme for it.

Check it out here.

https://github.com/equinusocio/material-theme

Material Design
Material Design Theme Sublime

 

Debugging

Visual Studio Code comes with full debugging support to view your code being compiled step by step or at certain specified breakpoints if you so choose. Go to the extensions tab and search for any debugging type extensions. These extensions can be specific to languages such as C# or Node.js.

VIsual Studio Code Debugging
debugging-extensions

When an extension like this installed VSC is given an debug adapter which defines a debug type. When debugging begins VSC looks up that adapter based on its type and launches the exe as a separate process. This is how the debugging begins.

To start the process we should navigate to the debugging tools by clicking the fourth option in our Visual Studio Code sidebar. This will bring you the debug screen like so:

By assigning a configuration and launch the debugging you should see your launch.json file. This contains all the attributes for your debugging session. You can also view which properties are available by using VSC Intellisense ctrl + space.

Intellisense debug json properties
Intellisense debug json properties

VSC has implemented a extensive but user friendly debugging interface. If you have any experience of debugging in its big brother IDE or have even just debugged with Java, C# in other environments they aren’t world apart. VSC debugging features highlight its rich array of options in comparison to other text editors.

At the moment I use VSC debugging capabilities to debug Typescript through VSC and Chrome for an Angular 2 application. For more information on debugging TypeScript check out this blog post from one of the Microsoft devs.

Jaime Tarquino https://blogs.msdn.microsoft.com/jtarquino/2016/01/24/debugging-typescript-in-visual-studio-code-and-chrome/

The ability to debug in a IDE like environment opens up a lot of opportunities for developers as previously using languages like C# in a text editor was unheard of because of the lack of debugging options. For more detailed instructions on debugging in Visual Studio Code check out the official documentation here: https://code.visualstudio.com/Docs/editor/debugging

Git

Visual Studio Code allows you to link your Git repository with relative ease. It is the 3rd option in the user friendly navigation bar on the left hand side of the editor.

 

Initialize Git Repository
Initialize Git Repository

The button initializes the init () function Git command It will add all your files into your repository. As someone who is more used to using Visual Studio IDE’s team sharing services, having GIT implemented seamlessly into the user interface is incredibly useful and appreciated.

The notifications on what files are available to check in/commit to your local repository is an insightful tool-tip. You can later full push your changes to your GIT account from your local repository. By clicking the icon with the 3 small circle in a horizontal line we get access to full list of Git commands

 

Visual Studio Git Commands
git-available-commands

 

Sidenote

If you have ever tried to use the snipping tools to capture a internal menu but it kept disappearing every time you clicked new than fear not. When you are trying to make some sort of documentation and have the snipping tool open just press CTRL + Fn + PrntScrn. This will activate the snipping tool and you capture your snip from there with the menu in screen. This is an old but relevant tip for the creation of any documentation or blog post. Kudos to Micheal Greene for reminding of this :

https://blogs.technet.microsoft.com/migreene/2007/05/12/how-to-use-the-snipping-tool-to-capture-context-menus/

Context menu in Visual Studio Code with a snipping tool.
Contextual menu in VSC

 

So these are some of the main points of Visual Studio Code that I thought I should share. I’ll be sure to cover each subsequent version released to see what new features are being implemented. But it is a fine looking editor both practically and aesthetically and I find my self more accustomed to this dev environment as I siphon through my code (Angular 2 / TypeScript at the moment). If you have any thoughts or contradictions where VSC falls compared to another editor be sure to mention it down below.