Angular 2 Component Data Binding with Sample Whiskey Application

WRITTEN BY GARETH DUNNE @JSDIARIES

In our previous Angular 2 posts, we concentrated on the setup and structure of our application. You can find that here.

If you are already familiar with component data binding you can always check out latest Angular 2 practices in ngBook.

Now, we are moving onto something a little more visually apparent using some sample Whiskey data.

Our site looks something like this:

whiskey-list
whiskey-list

Here is our mock whiskey catalog used as the data for displaying the 3 different whiskeys.

whiskey-catalogue.ts

Whiskey.ts

We want to display these whiskeys from our mock data in our whiskey-list.component.

whiskey-list-component.ts

 

This component contains a class that initializes our imported Whiskey and WHISKEY_CAT classes.

From here, we want to be able to click on one of those whiskeys displayed to focus on it and display it in bigger dimension right above it.

We then want the clicked whiskey to appear inside a different div in a completely different component (whiskey.details.component).

This would be considered common practice in a typical website displaying a product catalog. They would have a style transition that highlighted one products chosen in a list by the user.

When understood, this should give you a good feel of how data flows down through components in an application. It will also show you how to utilize directives, while also showing you how the process behind how an event is handled in Angular 2.

Exposing selected data.

Our variable selectedWhiskey is assigned to a TypeScript export of a our Whiskey object. Just from being declared inside the WhiskeyListComponent class, selectedWhiskey is already exposed and accessible from our whiskey.list.component html file. We can bind our selected whiskey properties to our UI. In this case image src, whiskey name and description.

But how will this component get access to the information from the clicked on whiskey? We need our application to take the properties of the item clicked on and to then pass it to our whiskey.details.component.

The @Input() decorator was added to our whiskey-details.component . @Input allows us to define an input for a given component. So our selected whiskey value can be put in as an data attribute and the value of it flows down to our component.

This is an attribute binding that passes down the value of the selected whiskey

We need to create a function to set our selected whiskey.

whiskey-list-details.component


But what else is going on here? Well the object passed in our setSelectedWhiskey click method is referring to the singular whiskey at the current index using our *ngFor looping directive.

So when our *ngFor directive iterates through whiskeys in our whiskeyCat, whiskey is always referring to the current whiskey. When clicked the current whiskey is passed down to our whiskey-list-details.component.

We should now be able to see the selected whiskey in a different div from a our whiskey-list-details.component.

This is a very handy way of sharing a specific piece of data to another component. This is just one practical use of data sharing between components.

There are many other uses that I won’t cover here but make sure you check our resources page for any relevant reading material on Angular 2.

http://jsdiaries.com/resources/

So to reflect back, the @Input decorator tells Angular to treat selectedWhiskey as an input binding.

 

This means that it has access to event data. Once this is bound to our nested component, our nested component can now receive event data for example in this case its the selected whiskey clicked.

I won’t go too far into how decorators work in general. You can get pretty far not understanding what they actually are doing past the layer of abstraction that Angular provides us.

In the case of selected Whiskey we have specified it as an input binding.

There are many different types of decorators and you should really look at Todd Motto’s post to further unmask some of their mysteries.

https://toddmotto.com/angular-decorators

Overall, this is a simple example of how you would use Angular 2’s data flow decorators to control the flow of data to a nested component.

In essence, they are just a function that provides itself with instructions on what type of information it should expose it’s targeted variable.

Conclusion

This is a very basic version of this Angular 2 Whiskey application there isn’t a whole lot functionality here apart from the displaying the selected whiskey.

However, I plan to incrementally add bits functionality as I learn more about Angular 2 and its various techniques. I’m finding it be a very solid framework to be working with and something that I’m trying to specializing in.

The combination of TypeScript decorators and Angular directives really opens up the possibilities of your UI interacting with your data in different ways for creating feature rich applications.

Early GIT version

Here is very an early draft of this sample application for reference.

Angular 2 Upcoming Features and SemVer

WRITTEN BY GARETH DUNNE @JSDIARIES

Whats New?

January has been a fairly quiet month regarding big notable Angular news. This is partly because a lot of revelations were revealed in November and December, highlighting the version changes of Angular 3, and 4. Or more sensibly now called just plain Angular.

http://angularjs.blogspot.ie/2016/12/ok-let-me-explain-its-going-to-be.html

MIT License

As of January 11th, Angular 2 switched back to an MIT open source license framework. While this has no bearing on any technical aspect of Angular, it does reassure developers how they can extend and modify Angular without any worries.

The Google Angular team actually prefers the Apache 2 license for scaffolding the legality of an Angular 2 project, but it was understood that the wider community has a better understanding of the MIT license.

While hardly a major cause for celebration, this is still a nice example of Angular reacting to community feedback. In short, a better recognized certification says you can happily publish your Angular applications without restrictions.

You can see this license here.

Material IO

The Angular Material 2 beta has started, using the Angular CLI to install it. The beta provides high quality UI components using Angular 2 and TypeScript. These UI components are customizable within the Material Design specification. They also do not put a strain on the application by having low performance costs.

While Material Design definitely isn’t suited for everyone’s taste, its certainly nice to have the option as its neat, clean and has high usability Although, I think it limits creativity for UI designs to some extent.

In the context of an Angular 2 applications, functional design is incredibly important. If you value quick functional design over a design that has more visual fluidity and better creative processes, then you can’t go to far wrong implementing material design into it.

Heres some nice examples from the referenced sample application from the git.

material-design-sample
material-design-sample light
material-design-sample-2
material-design-sample-2
material-design-loading bars
material-design-loading bars

https://www.npmjs.com/~angular2-material

https://github.com/angular/material2

SemVer

Towards the end of December, Angular 2.4.0 became available. This was a stability injection that coincided with Angular’s new semantic versioning.

In case you missed this check it out here.

A major release cycle schedule was announced, pinpointing the exact times where Angular are planning its forthcoming major releases.

Also you can check out a video detailing Angular 4 and version plans here.

A deprecation policy was also introduced so that any major releases that contain breaking changes to the API will automatically be notified well ahead of time.

If one had to guess of what a deprecation issue would look in the next major versions, then we could probably look back to when packages such as uibootstrap or ng-dialog from Angular 1 etc weren’t fully compatible with Angular 2. Similar forthcoming breakages might be comparable to these kind of previous issues.

It will be interesting to see how this effects the Angular job market, as there is plenty of Angular 1.x roles still available and probably will be for a very long time.  In terms of maintaining projects and applications, many will still be developing on that version.

However,  more Angular 2 positions are being listed everyday so it is likely that some previous features might be deprecated. This might accelerate the process of some companies adapting some of the latter versions.

One of our goals at JSdiaries is to bring Angular 2 developers together and provide them with valuable information and news from the JavaScript world.

As we grow, we hope to implement a job board that will have listings of some open Angular positions. Hopefully, this will connect potential employers with some of the developers from the JSdiaries community.

Angular 2 – Module and Route Structures

WRITTEN BY GARETH DUNNE @JSDIARIES

In simple terms, modules are the basic building blocks of our Angular 2 application, whereas routes provide us with paths to point to specific parts of our application. These are both core to an Angular 2 application. It is important to create both with good, clean separation of concerns in mind.

Routes

A standard application has different layers of components (or functionality) that the user can navigate to. This is where our routes come into play. These routes provide url paths to direct us to these different parts of the apps functionality.

Say we are creating an application that displays a list whiskeys. When the user clicks on a whiskey in the list, we want to display a page showing the detailed information about that whiskey. That’s just one piece of the application.

How about the user wants to search for a whiskey he has previously purchased? That’s another piece of similar functionality. Because these components are closely associated with each other in terms of purpose,  it makes sense to create relevant routes in the same folder.

As a project of reference, I will be referring to my Whiskey shop application for example of the structure of its project directory. I hope to fully publish this within the next few weeks.

So for a basic application, we can just declare all these routes in our app.module.ts file (Our entry point for the application) . But what about more expansive applications with many different components to be directed to? We can then create a routing TypeScript file specific to a folder of similar components. This creates a routing system that is compartmentalized rather than declared in the one place.

For instance, say we have an actions folder containing a login, register and profile component. We can then create an  actions.routing.ts file which contains the relevant route paths.

Actions Folder Example
Action Folder Declared Roots
Actions Routing File Declared Roots

From here, we can export this routing file and include it in our App modules component.

For more detailed information on the Angular 2 router check it out here.

https://angular.io/docs/ts/latest/guide/router.html

Modules

A module provides meta data for a particular section of your application. It is then exported and can be accessed by another component by importing it. This imports/exports system is made possible through TypeScript syntax.

The process of importing classes/components into other classes and components closely resembles something from Object Oriented languages Java, C# etc.

./ in an angular import means current directory. This is obviously something you’d be aware of while making an Angular 2 application but its nice to be reminded due to the amount of time you can waste trying to get the correct directory path.
By declaring similar components in the same module you get to have a cleaner components and separated logic. You can declare all imports that are relevant to those modules.

 

So as you can see we have consolidated some of our modules into groups. Our LayoutModule and ActionsModule contains more than one referenced component.

For example our LayoutModule contains all of the following modules from our layout folder. Just to note the layout folder is just name I gave the folder in this instance and is not an Angular 2 specific structure recommendation.

Layout Folder Structure
Layout Folder Structure

The components from this layout folder (FooterComponent, HeaderComponent, NavigationComponent) were declared and exported here:

This enables our app.module.ts file to be significantly cleaner because we don’t have to declare each individual component that we have in our application.

Another advantage of these components segmented by similar functionality  is the ability to remove one from declarations if the developer wants to stop the use of certain piece of that particular functionality.

So just to reiterate we should assort all our module providers routes in RouterModule Object specific to that group.

We also no longer have to declare our routes here as we have our routes declared in our specific group components.

It is also regarded as good practice to separate your routes specific to what folders they are grouped in.

This allows you to have an Angular 2 application’s app.module file to not be overloaded with path references linking to different areas of your application. Instead, these routes will be located in a location thats relevant to the components it links to.

Our application is now nearly completely compartmentalized through the grouping of our modules and routes. Different types of functionality can now be targeted and contained within these groups.

Resources

I highly recommend this YouTube Angular Series by Lyrad Digital. The series provides some very useful information step by step, with the early videos in the series covering the best practices of routes and multiple modules.
https://www.youtube.com/watch?v=33ADKstmXqQ&t=2351s

You can also check my resources page here:

Visual Studio Code Features Part 2

WRITTEN BY GARETH DUNNE @JSDIARIES

Rich Features 

We will continue to look at more features of this wonderful text editor that is Visual Studio Code. If you missed part 1, for any god forsaken reason you can catch up here.

We will focus on some more of the nooks and crannies hidden in this source code editor

Keyboard Shortcuts

You may want have identical keybinds for indenting code as well as commenting and uncommenting etc. On Windows highlighting the desired code block to be formatted and holding the keys  Shift + Alt + F  will format your code by default.

Format Code Segment

However, if you have previous experience working in the Visual Studio IDE you may wish to change this to  Ctrl + K +. In order to do this, we can navigate to File – > Preferences -> Keyboard Shortcuts from here we can create a custom keybinding to override the default settings.

JSON Keybindings

Commenting Code Segment

Ctrl + K + C 

Uncommenting Code Segment

Ctrl + K + U 

These are just some of the most common ones that I use most often. Here is a detailed cheat sheet by Donovan Brown for many more useful shortcuts.

http://donovanbrown.com/post/visual-studio-code-keyboard-shortcut-cheat-sheet

Custom Settings

VSC allows us to change the default settings by navigating to File – > Preferences -> User Settings. This will give us a window like so:

VSC JSON Settings
VSC JSON Settings

Any changes we make in the right Window will override the default settings in the left. If we use the command Ctrl + Space  we get a full list of possible properties we can edit. This is extremely useful as this one key command provides a full list of customisable options for our text editor.

For example a useful change would be to change the property files.autoSave to “on” so that all our files are saved automatically. Simply apply this in the right window in the split editor and your files will no longer have to be manually saved.

File Auto Save

You can siphon through the intellisense options to get a feel of what you would like to change. For some handy tricks and tips there is a nice tech talk that covers all this here:

Extensions

Chrome Debug

https://github.com/Microsoft/vscode-chrome-debug

The breakpoints will be used in VS Code and you won’t have to switch back to chrome to debug. This proves quite useful as you don’t have to switch environment/context when initializes a debugging session.

In order to utilise this extension,  start Chrome with remote debugging enabled.

CSS Peek

https://marketplace.visualstudio.com/items?itemName=pranaygp.vscode-css-peek

An absolutely invaluable extension for your VSC environment. It basically allows you to go to definitions of your CSS classes from the ID’s in your HTML and vice versa. For example, if I hover over a class in my HTML file, it will display all the css that pertains to that class in a popup window.

Git History

https://marketplace.visualstudio.com/items?itemName=donjayamanne.githistory

Another useful extension to install after you’ve initialized your git repository. You can view all your previous commits in a detailed window. In VSC press F1 followed by the command

This will give an overview like so:

GIT-History Extension
Zen Mode

As of version 1.8 Microsoft introduced Zen Mode. This hides all of the UI for a more focused experience. To enable Zen mode press Ctrl + K + Z

If the full screen inhibits your ability to channel your inner Zen you can also turn that off by setting window.fullScreenZenMode like so:

VSC Zen-Mode
VSCode-Icons

https://marketplace.visualstudio.com/items?itemName=robertohuertasm.vscode-icons

Icons Extension

More of an aesthetic extension then anything else, this extension assigns each file an relevant icons beside it the file directory and in the editor top bar. It is frequently updated and the icons are of high quality.  Definitely worth your while if you wanted to add some more visual fidelity to your work space.

Color Theme

https://code.visualstudio.com/Docs/customization/themes

Color Theme Example

Not so much of an extension but its still nice to see that VSC has a live theme view enabled with some nicely polished themes already integrated.

Snippets

 VSC comes with a fully supported snippet implementation system. This will appear in the Intellisense as your typing or you can you type  F1 followed by Insert Snippet. VSC will then display various snippets relevant to language of this file that you currently have open.

Inserting Snippet
Inserting Snippet

I hope this highlighted some of the more attractive aspects of VSC as a text editor, practically and aesthetically. It is robust with options and tweaks that you can fine-tune to your own personal taste. Never have I used a text editor that had so much going for it, even without any extensions, by a country mile, it is still my text editor of choice.

Meteor.js – Meteor and Reactivity

WRITTEN BY GARETH DUNNE @JSDIARIES

Real-time Features

A lot of Meteor’s strengths hail from its reactivity and real-time capabilities. We will look in to how these work while explaining how these real-time features can integrated with an API.

Reactive Templating

Reactive or declarative templating is a style of UI construction that contrasts the imperative approach in other words declarative templating communicates to and tells the computer how to do something and as a result what you want to happen will happen. The declarative approach however tells the computer what you want to happen and lets the computer figure out how to do it. Declarative templating separates the UI state, the underlying logical situation of what the user can see, from the layout being viewed (DOM). The user declares how the rendering technology should translate the state into the visual elements of the DOM. The state is then updated and the DOM adjusts accordingly.

Declarative Template Diagram
Declarative Template Diagram

A declarative rendering framework manages its complexity with an internal model of the core state of the page and this automatically changes the UI to reflect this model. To simplify this, what you see in your user interface or HTML markup will update itself automatically when our data is changed or edited.

Instead of waiting for a hard refresh our UI will reflect what has changed. The endless possibilities and ideas for real-time applications really become apparent once the functionality of declarative template is understood. Imagine all the possible data that we can extract from from an API. For example the Twitter Stream API.

Twitter Stream API

To install this open up your cmd window with Node.js installed

The Twitter Stream API returns a JSON object full of various different components of specified user’s Twitter timeline. Each different entity is stored in its own separate array.

Each additional object key in an entity is also stored in a nested array. The application has to iterate through various layers of nested arrays to retrieve the specified key of information that is to be displayed.

Twitter Stream API JSON object
Twitter Stream API JSON object

This depicts a sample Twitter Object that would typically contain keys holding different variables of a tweet own. In the next post I will be covering more detailed methods showing how to use the Twitter Stream API.

Asynchronous Tasks

A typical Meteor.js application’s sync design is based on a singular JavaScript framework. JavaScript is usually single threaded and can only handle one event handler at a time. In a single-threaded environment, only one section of code can be running at any one time.

Single threading incurs blocking or synchronous tasks which means the system has to await a particular task to be finished and is unable to perform other tasks while waiting for it.

An asynchronous task can be initiated and then put aside while another task is executed. This is the concept behind Meteor’s synchronizing and event design.

In an application the Twitter Stream API can be used to retrieve information from Twitter timelines.

For a typical JavaScript framework the request would be made to the API and then the system would have to wait until it made a callback. This is not the case with Meteor, due to asynchronous use of the event loops. When the API makes a callback , that task can be concentrated on again. In order for this to happen JavaScript generates an additional background thread which takes care of managing the tasks of the event loop in order to prioritize the API tasks only when it has made a callback to the server.

Here is sample diagram of a the realtime sync by Toptal

Toptal sync diagram
Toptal sync diagram
Live refresh

Since Meteor is based on the Node.js framework , the server at runtime is single threaded. As a whole,  Node.js usually has more asynchronous operations, calling APIs and reading and writing files. So a basic callback can consist of up to three nested functions while more complicated operations can contain even more levels and sub-levels of other callbacks.

This may initially sound complicated., However, Meteor simplifies this by using a fiber package to deal with the way callbacks are made in this regard. The fiber package solves the issue of excess callback functions by abstracting away the asynchronicity using the Fiber sub-library called Future.

Meteor’s server automatically detects changes to any applications codebase, so pushing the new code to the clients prompts the client to reload. Even after an application has been deployed changes can occur and automatically update the applications client via hot-code pushes.

Conclusion

This post contains key fundamentals that will be used in the implementation of a typical Meteor.js application. Its good to know some of these concepts about reactivity that work under the hood of the Meteor.js architecture.

This post also reflects how a typical application will be implemented using Meteor.js and its unique isomorphic API.  It is used to structure the code and provide a dynamic reactive coding environment, giving any application that you make fluid real-time capabilities.

It will also make it easier to maintain and enhance in any future phases of an application that you have created where additional functionality might be considered. The Mongo vs Minimongo relationship that a typical Meteor.js application contains, provides a foundation to easily store any retrieved object or entity from an API. While the reactive environment allows any changes to these objects to be reflected back into the user interface instantaneously.

In the next post we will look at a more detailed implementation of the Twitter Stream API.