Angular 5 HTTP Form Inputs & RxJS

Angular 5 Form Inputs

Whatever framework you are using, forms are a key component of any website or web application.  They provide us with one of the most important aspects of user interaction. We need to give the user a clear understanding of what information we require, while also validating his/her data in the process.

If we want to provide a real-time interface for the user that reacts to his/her inputs and selections, we can use RxJS Observables and Angular form controls.

This tutorial is based on my application Beer Name Finder which you can view here:

.

The application takes user input, sends off a HTTP request while the user is typing and retrieves a new dataset based on their current search term in real-time.

The user can also change the beer category through a drop down selector in the same way to get a similar user interface update.

The full repository for Beer Name Finder is available here.

I think this is one of the coolest things about modern UI manipulation when combined with modern frontend frameworks. And surprisingly, it is not overly difficult to get running once it is broken down into different segments. I will detail how to go about that in this post.

And if you enjoy this dashboard, please consider giving it an upvote on Product Hunt here.

On a side note, if your looking to expand your Angular and Typescript knowledge I highly recommend this Angular & TypeScript book by Yakov Fain.

So, let’s begin.

Populate an Angular Input

Let’s say we want to populate a select dropdown field from a HTTP call. I used this process for my Beer Application so I’ll be using that as an example.

To start, I retrieved a list of beer categories from the BreweryDB API and applied them to a select dropdown field.

In our search.component.ts I declared the main variable types used:

The FormControl is the most notable declaration here:

It tracks the value and validation status of an individual form control e.g input field.

It is one of the three fundamental building blocks of Angular forms, along with FormGroup and FormArray.

I declared an array of type Beer from an imported TypeScript definition:

This maps our desired beer properties from our HTTP request to a beer object.

My imported type definition for Beer looked like this:

I then initialised my data service (beer.service) in the constructor:

I used a method in _beerService to retrieve the beer categories to populate the select dropdown field.

In my lifecycle hook ngOnInit I then invoke two custom functions:

The first initialization of the dropdown contains this functionality:

I got an initial dataset of beers from our getBeers() function I have covered this function extensively in another post here:

After this, I invoked the getCategories() method from the beerservice file which contains the following functionality:

This is yet another HTTP request similar to all others in the service.

this._baseUrl refers to the BreweryDB API endpoint:

The only unusual thing in the getCategories method is the Array.from(new Set(this.categories))

This could have been done a number of ways to get a new array object from an iterable but I used the Array.from() method here but this is just personal preference.

So now my categories object will now contain data from our request that look something like this:

If we now examine our markup for the form we can see this:

Just concentrating on the select field for the moment:

We can see that the *ngFor directive has iterated through our retrieved categories array. At this point, I navigated and selected a category option.

This next section is possibly the most interesting thing about creating a reactive input in Angular 5. It uses RxJS methods to track data from an input field and allows you to manipulate that data from that input field as an Observable.

We now are going to look at the method listenForInput():

So starting with:

This term value is a reference to our FormControl declared earlier in the file:

The debounce time:

Waits for a new change in the input field from the user every 400 milliseconds. If a change occurs before 400 milliseconds from the previous change it discards those values.

The distinct method:

Ensures that there is a new value in the input field before declaring that theres been a change.

Once this criteria is met, we are finally able to subscribe to the Observable:

From here I have invoked:

This is just another http call to retrieve a list of beers using the parameters term and this.currentCategory which will filter the response to the desired dataset.

I’ll show you this searchTerm method as well:

This seems quite complicated but its actually not doing much more different than any other of our HTTP calls in the service.

We are using the term from our input field in the api request:

We are making sure that the category property exists in the our respoinse:

But most importantly, we are assigning this new information to our beer observable source by using .next().

This beer observable is being subscribed to elsewhere in the application so the UI will automatically get refreshed which is very handy.

And when we have selected a new value currentCat(selectedCategory.value) will be called:

This is just one example of using RxJS and Observables to track  a users interaction with a form element and have the UI refresh accordingly.

On a side note, Observables in general should be used when there is more than one stream of data. This is when they are most effective. But its fun to demonstrate their power in an application such as this.

The full repository for Beer Name Finder is available here.

JavaScript in 2018 – What to learn?

WRITTEN BY GARETH DUNNE @DUNNEDEV

JavaScript 2018

As the end of January is fast approaching, I thought it would useful to highlight some of the latest features in JavaScript to keep your eye on in 2018. This is not a comprehensive list by any means, but here are 5 things I think will see another surge in popularity over the next 11 months.

React Native

React Native is already an incredibly popular JavaScript native app development library. But its newly released feature will really bring it into the forefront this year.

I am of course talking about the release of React Fiber. This is where React Native truly stands out.

React Native’s performance was always considered to be fast and has even been compared to native developed apps.

However, with the release of React Fiber, areas like animation, layout and gestures are now signficantly more responsive. It now has the ability to split rendering between chunks and spread it out between multiple frames.

This is not the only crowd-please; Fiber also assigns different priorities to different types of UI updates. The more important ones take priority when React re-renders.

For a more detailed guide to React Fiber I recommend this explanation here on the React Fiber Architecture.

To summarize, React Fiber works smarter, not necessarily faster. Prioritisation of tasks makes it a faster application. Very exciting stuff for those interested in fine-tuning performance.

Styled Components

Styled Components
Styled Components

The concept of Styled Components stems from the idea of components being reusable and modular. This is usually associated with best practices in the latest of JavaScript technologies.

As such, some of the industry seems to be shifting towards creating components that contain a certain piece of functionality that can exist in isolation. For example, a button or a menu.

In other words, this component can be migrated from project to project, needing little customisation to be fully functional. A component like this opens up many opportunities to inject different styles into it in various situations.

A library called Styled Components is using the idea of module styled React web components and I encourage you to check it out here.

While my personal preferences for styling are still SASS and partials, there is no denying that styled components are the inevitable evolution of modular UI components.

This a very useful one to know in 2018 as it injects scale-ability and modular practices into the styling of your individual project components. This ethos will not be going away any time soon as more technologies adapt the same behavior.

If Styled Components perk your interest and your not familiar with the ways of React.js you might find it useful to get started with this learning resource.

CSS Grid

CSS Grid is a relatively new layout system available in CSS. Unlike Flexbox, you work with a grid layout by applying CSS to a grid container (parent) and also the grid children which become grid items.

And although its not directly JavaScript related, I feel compelled to mention it here. It is a great addition to the layout of any web application or any JavaScript framework.

The basic premise seems solid, but why is this necessary? Well for one thing, it is the first proper layout system available from the browser. Flexbox was quite a one dimensional system in this regard.

It is also a cleaner way to create your responsive layout. This is because there are no additional untidy classes to add to your markup. In addition to this, there are no extra divs used to define something like a row. Instead, there only is a parent and a child.

And while it will be over a year before CSS Gris is implemented in production environments, its trajectory is really on a upward scale for 2018. There has been nothing but positivity for it and because of that I think it will really come to fruition this year.

I have started to change the grid system in my beer name finder application (built with Angular 5) from foundation to CSS Grid which you can see below:

Beer Name finder

I intend on doing a full post to CSS Grid but in the meantime this is a great comparison of CSS Grid to Bootstrap.

While this video from Coding Tech originally introduced me to CSS Grid:

GraphQL

GraphQL has been rapidly gaining popularity. When I first heard about it, I was really intrigued at the prospect of using a new query language for my API calls.

It makes sense to me that I should dictate what kind of query I want to send over to my API endpoint. Using GraphQL I can just define what format my requests and responses should be using a Type face query language which I would describe as hybrid between JSON and TypeScript.

There are plenty of examples on the site but I’ll give you a brief overview of one here.

You define your request Type like so:

You then use this Project Type in your GraphQL request;

And the data returned is logical and what you would expect from what you described in your request.

Makes sense right? I encourage you to play around with it here.

While I don’t have all that much experience with GraphQL, I can attest to it being a great service that can really streamline how you interact with data. This will make any frontend developers life that much more straightforward and is a tool to learn in 2018.

 

Electron

Hybrid desktop applications built with JavaScript are becoming less taboo among the web development community. Electron has seen particular success.

I have written a full post here about hybrid desktop applications and Electron.

Electron allows a developer to build a desktop application where the same codebase for the application is used to create iOS, Windows and Linux versions.

The mantra write once, use everywhere springs to mind here. And although there has been some concern for performance, this has been eased somewhat by big names in the industry creating applications that we all love and use.

Applications like:

Chances are high that you’ve used one of these in your daily life and haven’t noticed anything unusual in performance.

In 2018, I can see more popular applications adapting Electron for their desktop versions. Not only does it look like it will become even more popular but it also reinforces the unique flexibility that JavaScript has as a programming language.

JavaScript World

Once again, there doesn’t seem to be any slowdown for JavaScript while it progresses further into a wide variety of technologies and services. These are only some of my picks to watch out for and learn in 2018. Please let me know what your looking out for this year.

How to use Firebase to host your Web Application using a custom domain

WRITTEN BY GARETH DUNNE @DUNNEDEV

In comparison to a few years ago, there are a wide variety of ways to deploy a web application. Many will vouch for Heroku for prototyping and I tend to agree. Its a great service to deploy an app free of charge with the option to pay for premium features to scale up.

Another great option would be Github Pages which allows you to host a website or web application by deploying one of your repositories. It gives you a url to view your repository such as :
https://username.github.io.

Again, this is another great option for getting you application live.

The best option that I have been using at the moment is Firebase hosting. Its similar to the other options but allows you to stack extra services on top such as cloud functions. Heroku, of course, also lets you run similar server side functions and its backend and is a lot more flexible.

And although I might come back to compare all these providers the main thing to take away from these services for the purposes of this post, is that Firebase automatically provides SSL encryption. This makes it very easy to link it to a custom domain purchase from domain name sites. In my case, it was NameSilo, who I find dirt cheap without the shadiness of other low cost domain providers. Its reliable with a great albeit uninspired interface.

This is all taken from an experience I had when deploying my random beer finder web application.

This is an application that uses some nice animations from a frontend Coursetro tutorial in combination with RxJS Observables and requests to BreweryDB API.

Be sure to check it out here.

So lets deploy our web application and apply our custom purchased domain.

Setup Firebase

Full instructions from the Firebase documentation are listed here, however I’m just going to cover installing it via NPM.
Run the following command in your console window to install firebase tools globally:

Now, in the directory of your desired project, you now want to initiate hosting for Firebase:

From here you can dictate how you want you Firebase application to be configured.

Say yes to public directory and configuring as a single page app:

You should then create your project in the Firebase console here.

You project has now been initialized with Firebase. Once you are ready to deploy move onto this next section.

Deploying

When ready to deploy your Angular application to Firebase we want to build a production version of it.

Run the command:

You application will be built and the output is usually in the dist folder. You can now do a full firebase deploy with the command:

Or if you just want to deploy the hosting services

When finished your console will indicate what url your deployed application is being hosted.

In my case it was something along the lines of :

https://random-beer.firebaseapp.com

Custom Domain

So the final step in this process is to verify your purchased domain to Firebase. Firebase will also take in any other subdomains you might have and redirect it to your deployed Firebase app url.

We will need to navigate to the Firebase hosting console.

You will have to change the DNS records in order to indicate to Google that you own the domain name. We want to create a TXT record in our domain backend. This is made relatively simple in NameSilo and most other domain hosting interfaces will be quite similar.

Log in and navigate to the domain manager:

Select your desired domain and click the DNS Records option.

From here we want to add two TXT record with details from our Firebase console.

After about an hour Google was able to recognize these new records and establish that I was the owner of the domain. Google will then ask you add two A records with custom IP addresses that they will give you. From here we will do the exact same thing on your domain provider except adding two A records instead using the details from our Firebase console.

SEO

As you may be aware, a typically bundled and deployed JavaScript web app using a modern web frontend framework is not crawlable or index able by most search engine bots.  To solve, it can be a complicated beast, especially for Angular applications.

The most common approach in order to make your Angular app SEO friendly is to allow your server to generate your HTML markup dynamically. In some cases, this can be easier said than done and was mostly done with Angular Universal.

However, I found it needlessly cumbersome and I think I have found a great alternative specifically for Firebase hosted applications. The folks at Angular Firebase have come up with a fantastic tutorial for this using Rendertron. An external service that allows your site to serve dynamic SEO friendly markup only to search bots while serving your users the standard JavaScript version.

I really think this is the future of SEO for web application so I highly reccomend you watch this video.

Conclusion

Its proven relatively pain free process to transfer a domain name over to our hosted web application. This seamless process is one of the reasons I’m looking at Firebase Hosting more longer term. Apart from just hosting, there are many other added features such as cloud functions which are particulary useful for deploying server side code alongside your application. I hope to cover that soon.

Hybrid Desktop Applications – Another part of the JavaScript ecosystem?

WRITTEN BY GARETH DUNNE @DUNNEDEV

JavaScript hybrid mobile applications having taken the spotlight for the last few years with the idea of writing code once and using it among many platforms.

These hybrid application frameworks such as Ionic, use HTML, CSS and JavaScript to build versatile WebView mobile applications. This exact same stack is also available to be used to build desktop applications.

Specifically, the platform Electron is the leading framework for building hybrid desktop applications in this fashion.

Check out this Git here and a great introduction here.

Interestingly, this is yet another way for JavaScript developers to utilise their own array of tools to avoid native platform specific desktop programming languages such as C# and Java and to instead use Angular to create desktop based application that can be deployed onto OSX, Windows and Linux.

Popularity

First of all, you might be wondering if anyone is actually using technologies like Electron? You might be surprised, when looking at some well established products and applications that are using this hybrid tech stack I came across the following notable players:

Personally, I use at least two of these on a daily basis. Its quite impressive that some of these big names have already adapted Electron so quickly.

Most notably, however, is that Visual Studio Code (my favourite code editor to use) was built in Electron. This a text editor that is on par with its IDE counterparts in terms of functionality.

It is reassuring to know that there are already well-established applications out there but what advantages could Electron have provided them?

Productivity

To be honest, this is always going to be where a hybrid framework shines. In terms of managing resources, a dev team with the same skillset (HTMLJavaScript, Angular, CSS) can be spread out between web applications and desktop applications that can written once and deployed to multiple operating systems.

Cross platform sharing of code is always going to help a developer or teams productivity. Electron lowers barriers to entry for desktop development by providing these familiar tools for web developers. Their familiarity with these tools will in turn increase their work output and productivity.

Say what you like about how it fares against its native competitors, however, you must admit any company will be intrigued by that productivity boost alone.

For some companies this is enough of a compelling case to use it, despite some performance and stability trade offs.

Performance

This is quite possibly the most controversial aspect when Electron is compared to native desktop programming languages.

Some articles such as this would really try and put the nail in the coffin of frameworks like Electron before its given its fair share as an alternate way to create performant desktop applications.

And while the title of the article is offbeat and bit outlandish there is certainly a very good argument to say that hybrid desktop applications will never compare to its native counterparts due to things like having to use a web browser in a desktop app which puts a strain on resources as it is.

However, why exactly do hybrid applications have to match native performance? As memory allocation in our hardware is consistently getting better I see no problem creating apps in Electron. It can be a lot more efficient then natively developing every single possible version of an application that needs to be on OSx, Mac and Linux.

Again, I want to use Visual Studio Code as a focal point here. It of course is built using Electron and makes a strong case for being a tight competitor to major code editors like Atom and Sublime.

In terms of functionality it is as robust as major text editors such as Atom and Sublime, with seamless Git integration and an extension package window to boot.

Getting Started

I’m no expert on Electron and hybrid desktop applications in general. So this post just sums up what I’ve noticed so far. It really seems very promising and yet another way to hone your JavaScript skills and apply them to a new area of app production.

How it compares to natively developed desktop apps should only hold huge weight at a more enterprise level and even with this in mind, it doesn’t seem to stop some very big names for utilising it for major enterprise apps.

The most important thing to take away from this as a frontend dev is to know that you have yet another big section of tech product development that you can move into. Making us in more versatile in what we can achieve.

Ultimately, I suppose you have to ask yourself when will this JavaScript growth start to plateau? How many sections of development can JavaScript be adapted to? So many years ago it was boxed off as just a web-focused technology in conjunction with HTML and CSS, but its meteoric rise in other areas is now undeniable.

It’s unclear whats going to happen next but it is on a upward spiral so the future looks very promising. It may not be for the native purists because a lot of web based programming goes against what makes native languages for desktop great.

For such a promising framework such as Electron I haven’t found too many learning resources for it. Here are some of the best I’ve found so far.

I hope to cover more of this framework in the future.