There are NPM packages for implementing various analytics providers in Angular 2 but for simpler requirements there isn’t always a reason to include Yet Another Dependency.

At it’s most basic implementation what we usually need to do is track pageviews. To do so we need to watch the Angular 2 router (or your router of choice) and trigger a Google Analytics event.

In your index.html include the Google Analytics script but remove ga('send', 'pageview' ... ):

<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXXXX-XX', 'auto');
</script>

Next, in one of our application files (I would recommend the application root but not the application bootstrap file) we need to cachethe current route,add a router subscription and trigger an event if the route changes.

In app.component.ts:

import ...
declare var ga:Function;
export class AppComponent {
  currentRoute: string = '';
  constructor(router: Router) {
    router.subscribe((route) => {
      var newRoute = route || '/';
      if(newRoute !== this.currentRoute) {
        ga('send', 'pageview', newRoute);
        this.currentRoute = newRoute;
      }
    });
  }
}

The above is all pseudo code and needs modification for most use cases, but in general we need to:

  1. Include Google Analytics script in index.html but remove ga('send', 'pageview', ...);
  2. Add declare var ga:Function; to app.component.ts
  3. In app.component.ts cache a version of the previous route.
  4. In the constructor in app.component.ts add a router subscription and if the route changes, use ga('send', 'pageview', ...); to send the update to Google Analytics.

Testing your local environment against Xcode and Browserstack is great but at the end of the day they are still just emulators. If you need to test against an actual mobile device it is useful to load your current local environment on a mobile device and do your testing immediately before you push to a remote server.

The following instructions are pretty specific since most Front End dev where I work is done on a Mac but I imagine that the instructions would be similar for a Windows machine.

For the record there are third party plugins that you can do this with as well, but if you do not already have those installed as part of your workflow that should not stop you.

Mac to iPhone:

  1. Verify that your server is running locally, for example, http://localhost:3000
  2. Connect to the same network on both devices.
  3. Find your computers name by either looking in your sharing settings or opening up your terminal. Ex: acarlson-mac
  4. In a browser app on your phone go to {{your-computer-name}}.local:{{port}}

Mac to Android:

  1. Verify that your server is running locally, for example, http://localhost:3000
  2. Connect to the same network on both devices.
  3. Find your computers internal IP address by either looking in your sharing settings or using ifconfig in your terminal.
  4. In a browser app on your phone go to {{your-internal-ip}}:{{port}}

Quick tip: When working in Angular 2 if you get an error that looks like:

EXCEPTION: TypeError: Cannot read property ‘visitStatement’ of undefined

Or:

EXCEPTION: Error: Uncaught (in promise): TypeError: Cannot read property ‘visitStatement’ of undefined

Try checking your code for an empty ‘click’ event binding (<component (click)=""></component>). If the event is left empty it can throw that relatively nondescript error.

 

Sendgrid Labs has a great tool for stress testing sites and applications called Loader.io.

To get started all you need to do is upload a small text file with a unique key from Loader.io into the root of your site to verify ownership, then start running your tests. In the free version you can hit the application or site with up to 10,000 clients per for a minute at a time.

The free version shouldn’t be used as the end-all test for stress testing an enterprise level site, but it’s a convenient, easy to use solution for finding bottlenecks and glaring issues.

What methods are you and your teams using to define Sass and LESS or CSS color variables?

Colors are one of those things that can be interpreted differently pretty easily, and are used throughout your entire project.

One method that has worked well for some of my teams thus far is to use a single defined source to pick the names of the color variables based on their Hex code, then determine whether to camel case, hyphenate or underscore to separate words.

For example:

$gray: #888888;
$spunPearl: #a6a5ad;
$silver: #c6c6c6;

Pros of this method:

  1. If your variable names come from one source, there isn’t a question about what constitutes “gray” or “blue.”
  2. You don’t end up with duplicate colors throughout your CSS codebase.
  3. Variable names are abstracted from their components and can be used anywhere.
  4. Easy to remember – easy to search.
  5. You never need to think about whether or not something is lighter gray, lightest gray, or lightest-est-est-est gray.

What are some other methods being used to define things like color variables in your Sass projects?

Co-authored by Preston Chandler

When used appropriately, “No” can be our most powerful tool. Truly powerful “no” users employ it in the following ways:

No, but…

… we could always try ‘x.’

We don’t need to be a yes-(wo)men or flip-flop on our opinions but we do need to give reasonable alternatives to the desired course of action. Simply saying ‘no’ without any follow up leaves the decision completely one sided and prevents actual collaboration.

By providing an alternative we’re showing that we do care about the problem at hand and are actively looking to come to a compromise.

I don’t know…

… but I’ll find out for you!

Saying that we don’t know the answer to something can show humility. The only thing we know for sure is that we don’t know everything. However, we are very willing to learn.

No, because…

… x, y, z.

Talking others through our thought process will help them to understand where we are coming from. They still may not agree with us, but they will better understand us. The ability to back up our opinions with facts, experience and a logical position is critical when speaking with someone who expects us to be experts in our given field and instills trust in our knowledge.

Not right now…

… there are higher priorities

Many times a specific course of action isn’t incorrect, it is just not timely. Taking that same course of action at a later date may prove beneficial.

In addition to the specific language used, the following “Nos” will also help:

  • No Nonsense – Don’t be wishy-washy. Own the “No”. this is a great way for you to emphasize your role as an expert.
  • No Pride – Strong Opinions, Loosely Held. Recognize quickly when you are incorrect. It isn’t too late to change the “no” to a “yes”

This post on Angular 2 was co-authored by Landon Cline

It’s no secret that the JavaScript world is moving incredibly quickly to the point of exhausting anyone actively involved in developing products using a remotely ‘modern’ JS style.

With your JavaScript fatigue on the backburner, let’s talk Angular 2.

Why the fuss over a version change (Angular 1 > Angular 2)?

So much has changed in Angular 2 that it is important to think of it as an entirely new framework and leave what you know about Angular 1 at the door. While Angular 1 is still an awesome framework one of the core things Angular 2 tries to accomplish is to be more performant and offer guidance on a recommended architecture. Although it has not been released yet the Angular 2 CLI tool will help with scaffolding, generators and built in testing suites (Angular unit testing…not just a myth anymore).

For a reference guide on some of the syntax changes for Angular 1 vs Angular 2 checkout this article.

Major Decorators

JavaScript Decorators are an ES2016 construct, not specific to AngularJS. Angular 2 has several major decorators that they employ.

In Angular 2 Decorators typically declare classes that provide metadata about the component.

@Component({ … });

@Directive({ … });

@Pipe({ … });

@Injectable({ … });

@Input();

@Output();

@RouteConfig([ … ]);

Input

The Input() decorator declares a property binding usually sending data into a component.

// Your component JavaScript
@Component({
    selector: 'example-component'
})

export class ExampleComponent {
    @Input() title: string;
}
// Your component HTML
<example-component [title]="'Some title'"</example-component>

Output

The Output() decorator declares an output property that can be subscribed to using an Event Emitter (which implements RxJS).

// JavaScript component emitting an event
export class ExampleComponent {
    @Output() foo: EventEmitter = new EventEmitter();
    sendEvent() {
        this.foo.emit(value);
    }
}

Pipes

A Pipe takes in data as an input and transforms it in some way. String modification, for example.

There are several built in pipes including:

  • Date
  • Decimal
  • Percent
  • Uppercase / Lowercase

 

// Custom pipe
@Pipe({
    name : ‘customPipe’
})
export class customPipe {
    transform(value){
        return value.toString().replace();
    }
}
@Component({
    pipes: [customPipe]
})
// Pipe in use in a component
<p>{{foo | customPipe}}</p>

Routing

The Angular Router navigates users from view to view and allows passing custom data to individual routes.

Angular 2 routing is managed through the @RouteConfig() decorator. You do have the option of using either an HTML5 Location Strategy using the history pushState or the older HashLocationStrategy “hash bang” method.

@RouteConfig([
    {
        path: '/',
        name: 'Home',
        component: HomeComponent,
        useAsDefault: true,
        data: {
            hideSideNav: true
        }
    }
])

Dependency injection

Angular has it’s own dependency injection (DI) framework. You use the @Injectable(); decorator to mark a method as something that can be injected. After that you need to include it as a provider and in the constructor of the component you want to use it in.

If you want to use an injected component in the entire application it should be added in your parent component but not bootstrapped into the providers

// Your class where you declare the injectable component.
@Injectable()
export class ExampleComponent { … }
// The component you are injecting into.
@Component({
    selector: ‘my-app’,
    template: ``
    providers: [
        ExampleComponent
        ]
})

export class AppComponent {
    constructor(_exampleComponent: ExampleComponent) { … }
}

Projection

Transclusion in Angular 1 is now referred to as Projection. This allows a way for a parent component to insert markup into a child component. The <ng-content> tag is used to accomplish this and helps to keep your nested components flat.

@Component({
    selector: 'my-thing',
    template: `left  right`,
})
class MyThing {}
@Component({
    selector: 'my-app',
    template: `INSERTED`,
    directives: [MyThing],
})
class MyApp {}

Next Steps

There are a ton of resources out there for learning more about Angular 2. A few that we found very useful for our most recent project are:

Occasionally you’ll run into a problem where you have two or more ranges that you need to equalize. This is probably most common when charting or using graphs but also comes in to play when using things like HTML5 range sliders where you need to make a dynamic slider that has a range from 0 – 12 equalize to 0 – 100.

Taking the range slider example, let’s say we’re trying to capture how many hours a day something is in use. That means we would likely have a minimum value of 0 and a maximum value of 24.

The Problem

If we want to position something along the slider as it updates we would need to know it’s relative position, but we can’t just do a simple percentage because 0-24 is a very different range than 0-100.

So how do we find a relative position of the current value of the slider?

Enter Linear Equations (Point-Slope)

We’re going to be using the Point-Slope Form to find our relative location.

y - y1 = m(x - x1)

Where m is the slope of the line and

(x1,y1)

is any point on the line.

The first thing we need to do is solve for m because we already know x and y (our range values values).

To solve for m we would convert the Point-Slope form to the following:

m = y - y1 / (x - x1)

After that we need to multiply the slope by the current value.

Pseudo Code

This is a reduced example assuming you’re equalizing to a percentage.

var findSlope = function(min, max) {

    var x = [min, max];
    var y = [0, 1];
    
    return (y[1] - y[0]) / (x[1] - x[0]);
}

var findRelativePosition = function(val) {

    var slope = findSlope(0, 24);
    var min = 0;
    var max = 24;
    
    // We need to use (val - min) in the event our minimum value isn't 0. For example, if we want to use 12-24 as our hourly range.
    return slope * (val - min) * 100;
}

findRelativePosition(12); // 50
findRelativePosition(13); // 54.16
findRelativePosition(24); // 100

Animation style, acceleration, deceleration and motion are all very important things to consider when designing a user interface. Luckily most of these can be implemented using CSS transitions.

One of the easiest ways I’ve found to edit own transition and animation styles outside of the few keywords that have good browser support such as linear, ease-in, ease-out and ease-in-out is using Chrome DevTools cubic-bezier designer.

If we inspect an element in Chrome and apply a transition to an element we should see a small icon next to the type of transition.

Transition

If we click on the icon it will open an editor showing the current transition style.

Editor Open

From here we can select the handles on the line and adjust them and watch an example of the transition before it is applied. This value can then be copied out into our CSS!

Adjusted

If you’d like to learn more about motion and animation in UX design, check out Google’s Material Design Guidelines on motion.

Testing your local environment against Xcode and Browserstack is great, but they’re still just emulators. If you need to test against an actual mobile device it’s useful to load your current local environment on a mobile device and do your testing immediately before you push to a remote server.

The following instructions are pretty specific since most Front End work here is done on a Mac but I imagine the instructions would be similar for a Windows machine.

For the record there are third party plugins that you can do this with as well, but if you don’t already have those installed as part of your workflow that shouldn’t stop you.

Mac to iPhone:

  1. Verify that your server is running locally, for example, http://localhost:3000
  2. Connect to the same network on both devices.
  3. Find your computers name by either looking in your sharing settings or opening up your terminal. Ex: acarlson-mac
  4. In a browser app on your phone go to {{your-computer-name}}.local:{{port}}

Mac to Android:

  1. Verify that your server is running locally, for example, http://localhost:3000
  2. Connect to the same network on both devices.
  3. Find your computers internal IP address by either looking in your sharing settings or using ifconfig in your terminal.
  4. In a browser app on your phone go to {{your-internal-ip}}:{{port}}

  1. SSH into your server
  2. Install zip and unzip.
    1. CentOS / Fedora / Red Hat: yum install zip and yum install unzip
    2. Debian / Ubuntu: apt-get install zip and apt-get install unzip
  3. Zip a file: zip new-zip-file.zip file-to-zip
  4. Zip all files in directory: zip new-zip-file.zip *
  5. Zip a directory: zip -r new-zip-file.zip directory-to-zip
  6. Unzip to the current directory: unzip file-to-unzip.zip
  7. Unzip to a specified directory: unzip file-to-unzip.zip -d /directory-to-unzip-to
  8. List all files in the zip: unzip -l file-to-unzip.zip

Continuing on with my Adventures with AWS, I needed to point a subdomain to Amazon Web Services, while keeping my primary domain and it’s DNS handled at another host.

I would consider this is a relatively common need, you have your primary domain hosted somewhere that is handling your DNS for you, but you want to host certain parts somewhere else. This gives you flexibility to add new hardware, utilize cheaper / free hosting, and a whole host of other benefits based on your situation.

For the purposes of this example, the subdomain we’re going to point is aws.

It may seem complicated but we can do it in just a few steps as long as you have an Elastic IP already configured and added to your EC2 instance. If you don’t, check out my tutorial on setting up your Elastic IP’s first.

Pointing a Subdomain to AWS

  1. Log into your hosting account that handles your DNS for the domain you want to point. This may be where you registered the name, or it may be your current hosting provider.
  2. Open up your DNS zone and add an A record for the new subdomain. It should look something like: aws.yourprimarydomain.com. 43200 IN A {{ELASTIC IP}}
  3. If your hosting provider gives you a user interface to change your DNS settings, you’ll want to add a new record, or row with the name as aws (or your subdomain), the type as A and the data or value as the Elastic IP you have pointing to your EC2 Instance.

This can take some time to propagate, up to 72 hours, but if it’s a new subdomain it’s likely to propagate much quicker.

Disclaimer: You should think twice about interacting with the Slack API using client facing JavaScript like jQuery on a public website because your webhook (the special URL that Slack generates for you) will be public. This means that anyone could post anything in your Slack channel without being authenticated.

It is possible to interact with the Slack API securely using Node.js but the following tutorial is just provided for demonstrative purposes.

 

Slack is pretty great for teams, I use it all the time for work and just for groups of friends. At one point I was asked to provide a proof of concept for posting a message in Slack when a form was submitted through Contact Form 7 on a WordPress site.

In order to prototype this quickly without spending time to create a plugin and do it the ‘right’ way by using cURL with PHP, I decided to go the JavaScript route for a quick and dirty example.

This example assumes you have Contact Form 7 installed on your WordPress site.

Posting to Slack with Contact Form 7

The actual code that we need to use is going to look pretty messy because we need to minify it to make it work with Contact Form 7, so I’m going to explain it first.

var name = jQuery('.slack-name').val();
var email = jQuery('.slack-email').val();
var occ = jQuery('.slack-occupation').val();

var requestBody = "A request was made to join the Slack channel by: Name: " + name + ", Email: " + email + ", Occupation: " + occ + ".";

jQuery.post(
	'{{ WEBHOOK URL }}',
	'payload={"channel ": "#{{ CHANNEL TO POST TO }}","text ": "' + requestBody + '" }'
);

We start out by defining our variables and what we want to send to Slack. Because of the way Contact Form 7 creates it’s forms, we can’t just use the handy $.serialize() method that jQuery provides. Instead we need to manually grab the values.

Then in requestBody we form our text message that we want to send to Slack.

Finally using $.post() (a facade of $.ajax()) we make our request using the webhook URL that Slack gave us when we created the integration.

  1. Log into your Slack account in your browser and configure a new ‘Incoming Webhook’ integration. Choose a channel you want it to post to and change the name if you want, but for these purposes it isn’t necessary. When it gives you an Incoming Webhook URL, copy it somewhere safe.
  2. In your WordPress admin area, open the Contact Form 7 plugin and open the form you want to post to Slack from.
  3. Select the ‘Additional Settings’ tab.
  4. In your Additional Settings textarea, paste the following:
    on_sent_ok: "var name = jQuery('.slack-name').val();var email = jQuery('.slack-email').val();var occ = jQuery('.slack-occupation').val();var requestBody = "A request was made to join the Slack channel by: Name: " + name + ", Email: " + email + ", Occupation: " + occ + ".";jQuery.post('{{ WEBHOOK URL }}', 'payload={"channel": "#{{ CHANNEL TO POST TO }}","text": "' + requestBody + '" }');"

One important thing to note here is the on_sent_ok variable that we put before all of our custom code. This means that that JavaScript will only be processed after the form has sent, meaning we don’t necessarily need to worry about validating the field itself, if we’ve already handled that in the form.

After you’ve saved your form, you should see any form submissions pop up in the Slack channel until you remove the integration!

 

If your AWS EC2 Instance is unresponsive from the browser and you aren’t able to SSH in from your terminal, you may need to restart it.

This can happen for a few different reasons, one of which (the one I ran into) being memory management. I was running both Bitbucket and Jira on an EC2 Instance that was just too small, and became unresponsive multiple times.

Sometimes a ‘reboot’ won’t do it and you actually need to stop and start the instance. The difference is that a reboot doesn’t actually clear out your memory and will keep anything that you’ve been doing in memory.

Restarting Your Amazon EC2 Instance

Assuming you have an AWS Instance already created:

  1. Log into your AWS EC2 Management Console.
  2. In the left hand menu select ‘Instances.’
  3. Right click on the Instance you want to restart and hover over ‘Instance State’ and choose either ‘Stop’ or ‘Reboot.’ In my case I needed to actually stop the server and then start it again. Try a reboot first, just in case, but if that doesn’t work then try stopping the server altogether.
  4. Once it completely stops, right click and choose ‘Start.’ then try to log in again and continue debugging why it crashed in the first place.

An Amazon Web Services Elastic IP is essentially an IP address that is tied to your AWS account. It’s not specifically tied to any given EC2 instance and can be used for multiple instances.

When you launch your first EC2 instance you’re immediately assigned a Public IP address. This IP address is not permanent and if you restart your instance for any reason, a memory leak, hardware failure or anything else, that IP address will be dropped from your account and you’ll be assigned a new one.

This won’t do you much good if you want your site to be consistently accessible from the same address. That’s where the Elastic IP’s come in.

An Elastic IP is a permanent IP address that is tied to your AWS account. That means that you can start and stop as many EC2 instances as you want, that IP address will remain constant.

One thing to note, if you have an Elastic IP address in your account and you do not have it assigned to an EC2 instance, you will be charged for it. If you are using the IP you will not be charged.

Setting up an Elastic IP

Assuming you have an AWS Instance already created:

  1. Log into your AWS EC2 Management Console.
  2. In the left hand menu under Network & Security select ‘Elastic IPs.’
  3. Select ‘Allocate New IP Address’ and follow the prompt.
  4. Once you’ve allocated an IP address, in the left hand menu of the Management Console navigate to ‘Instances.’
  5. Right click on the instance you’d like to edit and select ‘Networking > Associate Elastic IP Address’ and choose the IP address you just created.

Congratulations! If all went well your instance will now be accessible from the static IP address. This will not change when the server reboots so you’ll be able to log in and manage your server much more reliably.

Hosting in 2016 is no small matter. There are a ton of great hosting providers out there, each with their own unique spin. The classics like Hostgator, Mediatemple, Namecheap etc are still around and doing great work but there are relatively new players in the field too like DigitalOcean, who just bill by the hour for a scalable VPS.

Billing by the hour for a VPS is by no means a new concept, AWS has been doing it for years but I’ve always been intimidated by the thought of not having a GUI like WHM or cPanel to manage them.

Until last week, that is. My VPS started running into memory issues because I had a LAMP stack running alongside my Jira and Stash installations. Jira and Stash are notorious for being memory hogs and I needed a solution fast to prevent any more issues.

My first thought was to spin up a droplet on Digital Ocean but a friend suggested I at least take a look at AWS. I started looking at the pricing and knew I’d need at least a 2GB VPS. On AWS I can get a 2GB virtual server for ~$13/mo. On DigitalOcean it would be $20/mo so I decided to give it a try. Because it’s billed by the hour I didn’t have much to lose.

Turns out, it’s way easier than I thought it would be. You do need to get a little comfortable with the terminal but most developers have some experience with Node, Gulp, Grunt or other command line tools at this point.

Getting Started with AWS

  1. Log in to or register for AWS.
  2. Go to the EC2 Management Console and click on ‘Launch Instance.’
  3. Select the machine image that you’d like to start with. This means you can launch a Windows or Linux (Red Hat, Generic Linux, SUSE or Ubuntu) server. It’s basically your starting point for your server. For my purposes I selected an Ubuntu 64-bit server.
  4. Select the server family that you’d like to launch. This is what determines the size and configuration of your server.
  5. At this point you can either click Review and Launch to get started with your server, or you can configure additional options such as adding storage and determining which ports you want to be accessible.

All in all it took me less than 5 minutes to launch and SSH into my new Amazon instance.

AWS might not be for everyone, you do need to do a little more configuration and you don’t have quite as much support as some other hosting providers but you do have immediate access to the whole host of other services that AWS offers such as load balancing, S3 storage and so much more.

So far, I’m really enjoying my experience with AWS, I think it’s important to stretch ourselves professionally, which for me, meant digging deeper into server admin tasks and I managed to save some money in the process!

About 3 weeks back I saw a progress bar tracking the progression through reading articles on a site that, for the life of me, I can’t find right now. I looked around and wasn’t able to (quickly) find any jQuery plugins that did that out of the box in a way that I was happy with, so I wrote my own.

Introducing progressify

progressify is a small jQuery plugin that provides a visual representation of your progress through an article or page. It can be instantiated on the whole page, or just a single element inside.

It accepts several options, is very extendable for just about any purpose, and can be styled to your hearts content with custom classes, or by targeting the created classes directly.

Check it out on Github and give it a go. I’d be interested to hear any thoughts or improvements!

About a year ago I wrote a post about equalizing heights with jQuery. I decided to revisit that function and make it a little easier to use by rolling it into it’s own little jQuery plugin. It’s so small though (322 bytes at the time of writing), I’d almost just call it a utility.

Download:

You can download the minified version on Github.

Usage:

Couldn’t be simpler. Just use $('.elements').matchHeights(); to equalize heights using CSS min-height or $('.elements').matchHeights(true); to equalize heights using CSS height.

Have ideas? Want to contribute? Can’t get the damn thing working? Fork, report errors and open Pull Requests on Github.