Creating A Reactive Data Source in Angular 4 – Part 2

WRITTEN BY GARETH DUNNE @JSDIARIES

In this part of the tutorial we will be focusing on our API calls and how they interact with the brewery API.

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

You can see the final version of what my beer app is here. I took the designs and styles of this application from Coursetro’s MEAN stack course and was able to implement a service for interactions with the data and the Brewery API.

Proxy

First up, in order to get data from the Brewery API we want to enable CORS (Cross Origin Resource Sharing) in our browser.

To accomplish this we have two choices:

The easiest option here is to install a CORS Chrome extension here.

This will enable you to perform cross origin shares in Chrome without having to setup a local proxy. This is handy for testing an application locally but would obviously fall short if pushed to a production environment or hosted externally.

The second option, which is something I would encourage you to do is to setup a local proxy. This will allow you to easily enable cross origin resource sharing for all your browsers and doesn’t take long to create.

To do this lets first create a proxy.config.json file in the root of our project directory.

Proxy file location
Proxy file location

This is our proxy API json object. It contains properties that allows our calls to send and receive data to the Brewery API.

However, it won’t work without running the proxy file alongside our application. So we will need to execute this command to start it alongside our application.

Beer Model

Next we need to create a beer view model. This will basically act as an interface for our retrieved data. Properties such as name, description etc will feature here.

In your app folder create a file called beer.ts and put in the following.

We can now import our Beer class to any of our components to reference data retrieved from the Beer API. This is

Get Beers

We now want to implement a method that retrieves all beers from our Beers API. Open up beer.service.ts and change it to the following.

So we now have a getBeers() method and a handleError method for our beers API call.

In our if condition we first check if this.result variable already has a value. This is an important step because our service shares permanent data throughout our application so if the application has already been loaded then there is no point in making the getBeers API call again as the data is already cached in the our browser/service to be used.

We then take the _http variable of type HTTP that was created in our constructor and then invoke the get method using our beer API url details as the parameters for it.

The line .map((res: Response) => res.json()) takes the response from the Beer API server and maps it into an JSON array for us.

.publishReplay(1) will allow the data to be reactive. We will come back to this.

.refCount(1) has a similar function. It allows the Observable returned by the HTTP get request to keep its connection open, this will allow the data source to be reactive.

catch(this.handleError) this will catch any error from our request and run the this.handleError function. All you really need to know about this function is that it will filter down through the error message to the point where it will usually be the most informative. Usually, a detailed HTTP code error or associated.

If you noticed some of the variables declared above the constructor you should see

These are both core Rxjs features that will allows our data to be reactive. We will come back to these but for now just think of them as reactive variables that we will using later on in our home.component.ts

This is the basic version of our service set up with the functionality to retrieve an initial list of beers. It gives a good overview of how our service will share data. However, this on its own will not do anything without injecting it into one of your components.

We will be doing this in part 3. For now think of its as a piece of functionality that will share data throughout the application, the data will be made reactive by using Rxjs Subjects and Observables which are declared at the top of the file.

Creating A Reactive Data Source in Angular 4 – Part 1

WRITTEN BY GARETH DUNNE @JSDIARIES

One of the most important aspects to nail down in Angular 4 is the idea of creating reactive data sources. No matter what kind of data you want to show your user, in order to take advantage of web applications you should really have your data be dynamic and reactive.

In comparison to React.js, Angular 4 enables you to create data that is shareable to all of your components via a service . We will then use Observables and Subjects to make this data reactive. This is achieved using the external reactive JavaScript library Rxjs.

And while Rxjs is also available to be used with React, in my personal opinion it is much easier and it better fits the architecture to be used in combination with Angular 4.

In this tutorial I hope to show how you can make your own reactive data source using the Brewery API for data. In this part we will just start with setting up the project.

As per usual if your looking to expand your Angular and Typescript knowledge I highly recommend this Angular & TypeScript book by Yakov Fain.

You can see the final version of what end of this tutorial series here. I took the designs and styles of this application from Coursetro’s MEAN stack course and was able to implement a service for interactions with the data and the Brewery API.

https://github.com/garethgd/angular-4-beer-search

Source

As this tutorial will be broken down into a few posts, you can see the source code in the GIT here.

Brewery API

In order to retrieve data from a source via HTTP we will use the Brewery API. This will at least keep our data source interesting and offer plenty of different data options to be displayed.

Navigate to the developer API section here.

Brwery API Menu
Brewery Applications

After signing up for a developer account, create a new application with whatever details you like.

Register New Application
Register New Application

The documentation is quite verbose and you can find a wide variety of different ways to query the api for specific beers.

You can also test the results of any api calls via the api explorer. This is useful for when you are testing different query parameters to retrieve specific datasets of beer information

API Explorer
API Explorer

For now, we just need the api key generated by your app. This will be needed in order to make a http request to the Brewery API server so store this somewhere to reference later on.

Setup

In order to progress from here we need to have Node.js and the Angular CLI installed.

No better way to get started than to watch this starting video by Gary Simon from Coursetro.

Once set up, we need to scaffold our Angular application. This is very easily done through the Angular CLI.

We will open up our terminal and in our current directory we want to generate the project with the styles scss flag.

We have now generated a Angular project with a sass styling structure.

Next lets generate our home component. This is a component that will display an initial request of beer from the API.

From here, we want to generate our service that will hold all the logic for retrieving data that can be shared with any of our components.

This is a service that contains all our methods that we will use to request data from the Brewery’s APIs. When you open up this service you will see that the Angular CLI has automatically injected a HTTP object into the constructor for us.

Lets modify this service so it now looks like this.

This HTTP object in the constructor will be used to make the HTTP requests. Meanwhile we have added all the necessary imports in the top of the file that we will need later on for this service.

This is our basic structure set up. In part 2 we will add our API calls to have a list of beers transition into our homepage.

Ionic 3 – HTTP Requests – Retrieving a Photo from a Google Place

WRITTEN BY GARETH DUNNE @JSDIARIES

As I become more comfortable with Ionic 3 and its functionality, I wanted to share how to connect to the Google Maps API, retrieve a specific place and then to request a photo from that requested place.

In doing so, you will then know how define a HTTP object using TypeScript and using ES6 Promises in order to make a callback function that requests the photo using that HTTP object.

This functionality stems from an app that I made called CoffeeTrail.

Android Coffee Finder Application CoffeeTrail
CoffeeTrail

It’ll be on the iOS store very soon but be sure to check it out on Android here.

Setup Project

As always we can generate our Ionic 3 project using the command

We then want to generate our locations provider.

This is a provider that contains all our methods that we will use to request data from Google’s APIs. When you open up this locations provider you will see that the Ionic CLI has automatically injected a HTTP object into the constructor for us.

This is the object we will be using to make the requests.

We will also generate a location-details component that will display our requested images.

API Key

In order to have access to multiple API calls in our app we need to request a developer API key for Google Maps.

You can generate one by going to this page and clicking Get A Key , This is required for all place and photo requests and won’t work without one.

Google API Key
Google API Key

Get Place

We will create a getLocation method that will accept latitude and longitude as parameters.

We utilize a ES6 JavaScript Promise that will use the http object created in our constructor in order to make the request along with the details of the location which you can change for your own personal preferences.

You will of course have to reference the API key that you created earlier on in the apiKey variable of type string..

This Promise will return true or resolve when the the request has been completed and the data has been returned. The results of the data is mapped to a new json object which we assign to the this.data variable through ES6’s arrow functions .

This data will be resolved/returned when we call it in our location-details file.

We also can add the getPhoto method.

This will take in a photo reference string as a parameter in order to a retrieve a specific photo based on the location from the locations/location returned from our getLocation method.
So how do we get the photo reference from the data set returned from getLocation? Well we can do this in the locations-list file.

Display Photo

Our location-details.html file should look like this to display the retrieved image of the location.

Notice how we use the **async ** pipe with the current image template variable.

This is because some asynchronous data objects can be a bit tricky to display without async pipe. The data source is an Observable that contains an array so using the async pipe secures it so to speak.

We then use the ng-template (which is new to Angular 4) syntax to display error text if no image can be retrieved.

So in our location.details.ts file we need to use our getLocation method in order to get a place and then to send a photo reference from that place to the getPhoto method.

This is just one way to retrieve data from an API in an Ionic application. The use of Angular 4 in an Ionic 3 project enables a developer to makes a request for some data and then to easily share that data throughout the rest of the components using a service or in this case, using our location.ts. provider.

Angular 4 News Roundup April

WRITTEN BY GARETH DUNNE @JSDIARIES

Whats New?

As more and more developers are upgrading their projects to Angular 4 the initial confusion of this sudden incremented version has settled and has brought with it some handy but hardly groundbreaking changes. I covered this in another post here.

Although there isn’t much reading material specifically for Angular 4 I still recommend having a look at Yakov Fain’s Angular and Typescript book here.

Angular Attack

Over a 48 hour period developers were instructed to create an Angular application to be submitted and reviewed with the best receiving a wide range of prizes. There are a lot of impressive entries and some really nice user interfaces were created in that short space of time.

Be sure to check out the entries here and the prizes here.

ngConf

Claimed to be one of the biggest and original Angular conferences. ngConf took place on the 5th to 7th of April in Salt Lake City Utah.

With plenty of Angular related content and speakers your bound to find something useful for you.

Plenty of topical and insightful information can be found from these talks so be sure to have a look at some of the speakers when you find the time.

Here are all the related live streams that took place over those 3 days. Use this schedule list here to find a talk that you want to listen to from the recorded live streams.

Animation

As covered in a previous Angular post, the way animations are imported has been simplified in Angular 4. One of the best videos to come out this month regarding this is Coursetro’s Angular 4 animations video by Gary Simon.

He presents his videos very well and concentrates on the broader scope of the full stack developer, starting from conceptual design all the way to full development in Angular. Be sure to check our more of his content, most of it is free,

Angular 5

Almost unthinkable at this stage right? Surely there can’t be anyone contemplating details of another Angular version? Well there actually has been a few hints from ngConf .

The release window is estimated for Autumn 2017. Not much details are revealed but promises of simpler and smoother Ahead of Time Compilations were hinted at. And although it might seem ridiculous to think about another version already, this is the path Angular will be following form now on.

Every forthcoming version will contain small and efficient refinements to the previous Angular version every 6 months or so. Not much core changes but rather notable improvements to make your development life smoother. We can only hope that not much is broken in the process with each of these incremental versions.

For more information please check it out this post here.

More Angular 4 and Ionic content will be sure to covered here so subscribe to the mailing list if you haven’t already.

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.

Still looking to upgrade your AngularJS app to Angular 2? Check out this tutorial by Toptal here.

Ionic 3 Release – Whats New?

WRITTEN BY GARETH DUNNE @JSDIARIES

Ionic 3 has released and with it, has brought some impressive but not overbearing changes to the Ionic framework.

While sites like Toptal have previously covered performance differences between Ionic 1 and 2.
This post will cover the upgrade from Ionic 2 to 3 and the performance differences that come with it.

Similar to the Angular 4 release, this isn’t a core change to the platform, rather it is adding some improvements to your applications that will increase overall performance and allows hybrid app development to come a few steps close to being on par with its native development counterparts.

As always here is some useful Ionic reading material. And here is the official post from the Ionic team specifying all the changes.

Updating from Ionic 2

Updating from Ionic 2 is actually quite a simple process. This video from Paul Halliday simplifies the process even further:

Angular 4

Ionic has been updated to be compatible with Angular 4 and all the features that come with it. You can find our Angular 4 release post here.

And the official Angular blog covers it here aswell.

Lazy Loading

One of the most notable features of the release, lazy loading provides us with the ability to breakdown our bundles for our application even further.

This allows our application to only load certain bundles/modules when they are actually needed. When you lazy load, your application performance improves, particular as the app is starting up because all the modules that were previously loaded in our app.module.ts are not requested at once rather they are loaded on a page by page basis.

I would highly recommend checking out Paul Hallidays tutorial on this:

TypeScript 2.1 and 2.2 compatibility

As specified on the official Ionic blog. Ionic 3 has been updated to be compatibly with Typescript versions 2.1 and 2.2. This is inline with **Angular 4 ** being compatible with these versions as well. More information can be found here.

A Promising future

So that just about summarizes the main changse for Ionic 3. I don’t think anyone can deny the momentum and progression that this framework has going for it.

While originally I was concentrating on all things Angular. Ionic has really provided such a sleek way to use web technologies in order to reach such a wider userbase and to target them more personally through mobile applications.

If you needed even more detail regarding Ionic 3 changes please check our Joshua Morony’s detailed guide here:

I highly recommend all his content as it provides a huge insight into all potential features you might want to implement into your application.

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

Angular 4 Released – Why a 4th version?

WRITTEN BY GARETH DUNNE @JSDIARIES

Another version of Angular?

Angular 4 was fully released on 17th March. In this post, I hope to address any confusion or niggling worries regarding how this affects current Angular projects and how exactly these changes could benefit your next project.

Here are the official changes.

If you are baffled as why there is already a 4th version of Angular I covered semantic versioning in a previous post here.

Flat ES Modules

Most of the changes in Angular 4 comprise of performance improvements for the framework. Perhaps the most significant one is the introduction of Flat ES Modules that treeshake your application for you.

During the ng-build process, the compiler deems certain code unnecessary  because it has no usages. The compiler then removes this code in order to reduce file size and to make the application more lightweight.

Backwards compatibility

Since the scheduled announcement of Angular 4, the Angular team have been reassuring everyone that this change will not affect the way your current applications run. When upgrading your application to Angular 4, there will be a seamless transition for the most part.

This seems to be the case as I have only experienced one issue and this is with the AngularFireBase package which the developers for it has stated that they haven’t made it fully compatible with it yet .

If you have experienced this issue you can also follow this excellent tutorial by Coursetro to get Firebase working with Angular 4.

This tutorial is very insightful and solved my Firebase issue.

You may also experience a similar situation with some of your libraries and packages but the core features from Angular 2 seem to function just fine.

Animations

The way animations are imported has been cleaned up for Angular 4. Instead of importing the various types of animations such as state, keyframes, trigger etc,

 You now specify an import that contains tools and assets for animations in one package. This isn’t much but it does feel less cumbersome to set up an animation for a component.

The browser animations modules should also be added to your app.module.ts file for this to function properly.

Check how to do that here

Ngif

 When using the ngIf directive we never had the ability to add an else clause to the statement. This has been addressed in Angular 4, we can use the element <ng-template> to specify the name of our else condition by specifying it after the # symbol.

Please note that <template> is now deprecated and is replaced by <ng-template> 

Email Validation

Perhaps one of the handiest changes, an email validation directive was added to input elements. This saves us from having to manually create regular expressions to validate a users email address.

Simply add this to an input field element just like you would for the required directive and our email input field will automatically have validation.

This is actually quite a useful feature as it applies an email validating regular expression pattern to our element using just one keyword.

You can, of course still create your own custom expressions for validating emails and other input fields.

I hope this post has reassured you that this new version of Angular isn’t as significant as the version increment might make it sound. Some nice changes here lets us utilise some conditions and statements a bit more as well as cleaning up some of the imports.

Be sure to check our resources page for more Angular, TypeScript and JavaScript reading material.

Ionic 2 Hybrid Apps – Getting Started

Following on from some of our Angular 2 posts, the next logical step was to delve into the Ionic 2 framework to see what it has to offer.

 

What is Ionic 2?

Ionic allows the user to build Hybrid Mobile Apps. These apps are built with HTML, CSS, JavaScript and TypeScript and are contained in a native wrapper so the it can be installed and published on a mobile device, whether that be iOS or Android.

This is very advantageous for the developer as it allows him/her to create and publish mobile applications without having to be proficient in their native programming languages (e.g Java for Android).

You can always read up on it here.

Ever wonder where we get our icons from? Check out the Ionicons cheatsheet here.

Why Ionic 2?

Aside from the aforementioned hybrid mobile benefits there is quite a few things to get excited about here. Firstly, the documentation is very well laid out.

https://ionicframework.com/docs/

This allows us quick access to a multitude of structural components to use for an application.

For example, one of the most basic components, cards would use the following markup.

As you can see custom HTML tags can be used to generate this structure with outputting a result like so.

There is a whole host of different components like this with usage examples for most so be sure to experiment with different combinations

Getting started.

You’ll need to install the latest version of Node before installing Ionic. Once installed you will have open up your command line and type.

This may take a few minutes.

To create a blank new Ionic project in your current directory you should then use the command.

However, we also have other options to create our Ionic application. Ionic will generate some of the applications structure if we specify in a different command.

ionic-tabs-example
ionic-tabs-example

We can also generate a project that has a fully integrated sidebar using the command.

ionic menu
Generated Menu Start

Ionic menu sidebar
Menu Sidebar

These templates tend to be very useful when you want to scaffold a prototype as fast as possible.

Ionic Native

While the custom layout elements provide a variety of ways for you to creatively structure an application, the plugins or (Ionic Native) are also an extremely useful feature. They are a set of plugins that add native mobile functionality to your application. To install one simply use the command:

The plugin has now been added to the project. You can check it out in the plugins folder

Ionic Plugins Folder
Ionic Plugins Folder

Like most packages/plugins that you add in we have to import it at the top of the desired component where it will be used.

You can find a whole host of native plugins here.

I hope this post gave you an insight into how Ionic can benefit you for hybrid application development.

We’ll be sure to cover more interesting topics about it in our next post. Including how to publish to an application to the Android SDK. Be sure to have a look at our resource page for any other useful reading material.

Sass in Angular

WRITTEN BY GARETH DUNNE @JSDIARIES

in Angular

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

So SASS (Syntactically Awesome Style Sheets) are an already  well established and renown pre-processor for CSS. It allows the developer to create modular CSS where classes can nested inside each other. To summarize is benefits, it allows you to write less and customize more.

It also has a whole host of features including variables for colors, urls, fonts etc, while also having, mixins, extending/inheritence and operators.

You will write all your SASS code in a .scss extension file. The compiler will then output this into a css file based on the nested structure of your classes.

Having already seen the structure of Angular’s component based architecture you might wonder what exactly is the best way to implement SASS to an existing project.

And although I could show some of Sass’s great features, I will concentrate on whats important in the context of an Angular application.

You can check a great SASS intro here.

And here is a great book resource for learning Sass and Compass if you wanted to really hone your Sass skills.

Sass Structure

There are many different application you can use to get going with Sass you can pick your own preference here.

I personally use Koala its a nice GUI 3rd part application that looks for a scss file in a specified file directory and then compiles it to a css file.

Koala Sass
Koala Sass

Once you open Koala navigate to your desired project directory.

When you find the .scss file you want to turn into css, simply press compile once you find it in the directory. Koala will also has real-time compilation and will listen for the file changes in this folder.

It is also cross platform so it will run on Windows, Mac and Linux.

An ideal Sass structure would have folder called partials. Each file in this folder would have many different scss files that would be prefixed with an underscore.

Each file would adhere to a specific part of a website for example home, about, navigation.

sass-partials
sass-partials

All of these partials are then imported in the main .scss file ( usually called global.scss or style.scss). This one file is then compiled into a css file that is used for the whole project.

style.scss
Importing partials in our style.scss file

This is deemed as one of the most efficient ways to manage the styles of your project as all your css is compiled into the one file. However, in an Angular project there are two different approaches.

Generate Sass

The easiest way to get going with SASS in an Angular project is to create a project in your command line with the styles set to scss.

This will scaffold a project for you that will contain an app.component.scss file that will automatically be compiled for you without the use of a 3rd party application like Koala.

Manual setup

If you wanted to setup up your own styling structure once you create an Angular project through the CLI you should note that
each component generated has its own css file specific for that component. So if you create a Sass file with the component’s naming convention eg home.component.scss Koala will detect this and will compile it to home.component.css.

So instead of having a partial import system we just have individual sass files that are unique to the component.

I’m sure there is an argument for using both methods but this is the method I personally use. It makes the most sense to me as it aligns with the way an Angular project is typically structured and goes hand in hand with using the Angular CLI.

Form Validation

To give a practical example of using Sass in Angular I’ll focus on styles for form validation.

For validating forms in Angular we can use preexisting classes that correspond to the state of on input field or select box.

These classes are:

  • ng-pristine
  • ng-invalid
  • ng-touched
  • ng-dirty
  • ng-valid
  • ng-untouched

These classes are self explanatory for the most part, ng-touched is applied when the input field is written in, ng-dirty is applied when

The ng-dirty classes indicates when the form has been modified by the user. The opposite of this is the ng-pristine class which is applied as long as the form has not been modified by the user.

In Sass we can add appropriate styles to these classes to indicate when an input field is empty, invalid, not yet entered etc;

Here is an example of adding relevant border colors to these input states.

Form with styling states
Form with styling states

Overall

Although styling might seem quite arbitrary in context of learning Angular. Sass allows you to be more efficient and modular when it comes to creating a beautiful Angular application. Its a very useful tool to use in combination with Angular and fits in nicely to the structure of a component.

If you are looking for anymore resources to learn Angular be sure to check our resource page here.