Check out our Angular Book Series.

Creating Angular Directives Part 1 - A Simple Directive to Toggle State

I'm updating my Learn With tutorial books that teach Angular Development for Angular 8. I decided to do a deep dive into Angular Directives. This series of posts is a snippet of what will be in the full series, and is focused on creating attribute directives.

What is an Angular Directive?

An Angular directive is just like an Angular component, except with no template. A directive can be applied to any HTML Tag or template. There are two types of directives:

  • Attribute: An Attribute directive will apply something to an existing HTML Element, or even your own Angular component.
  • Structural: A Structural directive will modify the HTML body by creating, or removing, elements.

This series of posts will focus on creating an attribute directive.


First, create a new project with the Angular CLI:

ng new

You can follow through the instructions at your discretion, but you'll go through a wizard like this:

I named the project ud, for Understanding Directives. I set up routing and used regular CSS.

In the app.component.html file, delete everything except the router-outlet, so the file looks like this:


You can run the app, but you won't see much until we start adding routes.

Create the Attribute Directive

We're going to create a directive that will toggle an HTML Element between two separate visual states, done by changing different CSS elements on the directive.

First, we'll do some setup. Create a component for creating our own attribute directive:

ng generate component create-attribute-directive

You'll see something like this:

Open up the app-routing.module.ts file and a sample2 route to the Routes array:

const routes: Routes = [
{path: 'sample2', component: CreateAttributeDirectiveComponent},
{ path: '**', redirectTo: '/sample2'}

Now, use the Angular CLI to create our first directive:

ng generate directive directives/reverse

You'll see something like this:

I put the new directive in the directive directory. If nothing is specified it will be put in src/app by default, but long term I like to keep my code better organized without a lot of things in the main app directory. Open up the reverse.directive.ts:

import { Directive } from '@angular/core';
selector: '[appReverse]'
export class ReverseDirective {
constructor() { }

First, we import the Directive class. This is metadata used to define the directive. The only thing we define, at this point in the metadata is the selector. We'll use this when we apply the directive to an HTML element, the Angular module, something like this:

<button appReverse></button>

Right now, the directive doesn't do anything, but we'll come back to this in the HTML template later. It is strongly recommended you do not name your custom directives with a prefix ng because that is used by the Angular framework and we want to avoid conflicts with other existing directives.

I want to note that the directive is loaded in the main Angular module. Open up app.module.ts and you'll see it in the declarations section:

declarations: [
// other stuff

If you do not add your directive to the @NgModule your app won't know how to find it and you'll get compiler errors.

The first thing we want to do is inject the ElementRef into the directive class:

constructor(private el: ElementRef) { }

Dependency Injection for Directives works just like it does for other components, so we inject the value into the constructor. This will give the directive class a reference to the component which is was placed on.

This directive needs to pass in a value of the directive name, and then make changes to the ElementRef's styles based on that. To do that we'll need to define an Input() metadata. The simplest way to do this:

@Input('appReverse') reversedState: Boolean;

When the directive sees the appReverse directive applied to an HTML tag as an attribute, the value will be set in the reversedState value inside the directive class. In order to run some code whenever that value changes I'm going to switch it to a get/set method:

private _reversedState = false;
get reversedState() {
return this._reversedState;
set reversedState(input) {
this._reversedState = input;

The get and set methods are pretty standard. A private variable holds the state. The get method will return that private variable, and the set method will set it. The set method also runs a changeState() method, so let's look at that:

changeState() {
if (this.reversedState) { = '#000000'; = '#ffffff';
} else { = '#ffffff'; = '#000000';

This method checks the reversedState value and sets the background and foreground colors. I use nativeElement property on the ElementRef to drill down into the component and set specific styles. For the moment, I'm hard coding the color values, but we'll revisit that in a later sample.

How do we use the directive? Open the create-attribute-directive.component.html file:

<button (click)="reverseState()" [appReverse]="reversedState">
Reverse State

The appReverse directive is placed directly on the button; and it is given the value of reversedState, which is a Boolean value in the component that we'll create. The click button is used to call a reverseState() method that will toggle the reversedState property.

Open the create-attribute-directive.ts file. First create the reversedState property:

reversedState = false;

Then add the reverseState() method:

reverseState() {
this.reversedState = !this.reversedState;

We've seen this method, and property, set up identically in the previous sample. The major change is in how the new styles are applied to the button.

Rerun the app:

Click the button and the state should switch:

Play with it to switch the state back and forth.

Congratulations you did it!

What's Next?

While this is a simple example, it does show that we can create our own directive and use it to affect the HTML element is is applied to. This type of example is pretty common when you search for directive tutorials throughout the web, however by accessing the nativeElement directively it creates a dependency between your directive and the internals of Angular which may change.

The next article in this series will show you how to address this using the Angular renderer.

How do I redirect to a different domain inside Angular?

I was doing a code review for a colleague,and as part of his code he was redirecting the browser:

window.location.href = "";

This code was working perfectly fine, but when performing a redirect to another domain in an Angular component, there is a `more angular` way to make this work by using the Document service.

First import this:

import {DOCUMENT} from '@angular/common';

Then you need to inject that into your component:

@Inject(DOCUMENT) private document: Document
) {}

This inject syntax is a bit different than a normal Angular service because it uses the Inject metadata.

Once the document is injected, you can redirect like this:

this.document.location.href = '';

This is just an Angular layer of abstraction over the native JS way to perform a redirect; but when working within an Angular component I like to lean on the Angular abstractions. They help with unit testing purposes.

Get the code here.

How do I change the URL in an Angular Application without reloading the Route?

I'm working on an Angular app, as I often do and wanted to change the the route in the URL without reloading the application. In essence, the user has just created something, we wanted to redirect the user to the edit screen, with all the data loaded. The catch was that the edit screen and create screen were the same exact component, just with different data loaded. And we didn't need to load new data because the user just entered everything; and any database specific data like a primary key was just returned from the service. How can you do that? Use the the Location lib from the Angular library. I'm going to show you how.

The Setup

First, create a new Angular application with routing. Then create a view component--I Called mine view1.

Change the main app.component.html to contain the router outlet:


And add these routes to the routing module:

const routes: Routes = [
path: 'new',
component: View1Component
path: 'edit',
component: View1Component

We're going to load up the new route, and then redirect to edit on the click of a button.


In view1.component.html, add a button:

<button (click)="onSwitch()">Change URL</button>

When this button is clicked, we'll perform the URL change without loading the new route.

Move to the view1.component.ts file. First import the Location from @angular/common:

import { Location } from '@angular/common';

This is important, because for some reason IntelliJ is not importing the Location object properly, and nothing works if the import is missing, or worse lost.

Location is an Angular service, so inject it into the view1 component:

constructor(private location: Location) { }

Now, in our onSwitch, use the replaceState method:

onSwitch() {

This should work:

Play with the sample here.

How do you override a method in JavaScript?

I'm working on an experimental project and wanted to find out if I could override a method in JavaScript. I wanted to see if I could override the JSON.stringify() method to add my own functionality. It turns out you can and it is pretty easy.

First, let's create an object we want to convert to JSON:

let myObject = {
foo: "bar",
foo2: "bar2",
foo3: "bar3"
console.log('------ JSON.stringify output ---------');

Output that to make sure all is good:

Now, let's may a backup copy of JSON.stringify:

let myJSONStringifyCopy = JSON.stringify;
console.log('------ My Copy output ---------');

This is just a new variable that references JSON.stringify() and we can use it just as we would JSON.stringify():

Okay, but now we want to replace JSON.stringify(). Create our own method:

function myOwnReplacement(value) {
return "faker";
JSON.stringify = myOwnReplacement;

console.log('------ JSON Stringified Replace ---------');

console.log('------ My Copy output ---------');

Will overwriting JSON.stringify also overwrite our myJSONSTringifyCopy? Nope as these dumps prove:

Play with the sample here.

In the case of this replacement it isn't very useful, especially since the resulting output is no longer JSON. But, I'm working on something slightly more interesting that I hope to be able to share at some future point.

Note: I do not endorse doing this to your friend's application on April Fools day, unless you really want to.

How do I test the rxjs debounceTime() function?

I'm working on an Angular application, and sometimes we use the debounceTime() function. When a user is typing in a text box we may want to trigger a service call based on the characters we type. We use debounceTime() to make sure that user has finished typing for a certain length of time when the service call occurs. Our code might be something like this:

).subscribe( value =>
// do something
this.newValue = value;

The input here is most likely an element in a reactive form.

This says that when the observable is resolved, we wait 300ms before doing something. In that time, if the user types more characters, those characters overwrite the original ones, and we start waiting again. IF there are 300 milliseconds without any more typing, we move forward to the subscribe and do something.

This presented a problem when testing. Here is a sample psuedo test code:

it('should execute some code', () =>
input.setValue('some new value');
expect(newValue).toBe('some new value');

The problem is that the value is set and the expect is checked before we waited 300 milliseconds, and as such the test fails.

The solution is to run the test in a fakeAsync block and make use of the tick() function.

This should fix it:

it('should execute some code', fakeAsync(() =>
input.setValue('some new value');
expect(newValue).toBe('some new value');

The tick() function tells the code to wait, or pause, for 300 milliseconds before proceeding. This is the magic that made the tests like this work.

Warning: I wrote all this code in the browser, so is untested and may have some minor syntax errors; but the approach should be solid.

Why didn't my Angular View Update when I added items to the input array?

I was recently working on an Angular project where the view had an input array:

@Input() items: Array<items>;

The view of the component would loop over the array:

<div *ngFor="let item of items">
{{ }}

At some point in the app, user interaction happens, and the app needs to load more data. We had a result handler from a service call doing something like this:


If you output the results, you'll see that the items array had the new items. Try it here.

However, the view would not update the display to reveal the new items in the array. How come?

In short, the view did not know that it needed to update itself. The view contains a pointer to the array and was watching for changes to that pointer. While the items in the array changed, the array pointer did not. An easy solution was to change the way items were added to the new array:

items = items.concat(itemsToAdd)

Since we were updating the actual input value, the view would know that the item had changed, triggering a redraw of the screen.

That's how we handled it!

Can I use CSS calc() with vw and pixels?

I was working on a problem today where we wanted to offset the position of an ng material sidenav. The problem was we didn't know what we would want the offset to be, it would depend on the browser size on the clients computer which will most likely be variable.

I suggested using calc() with vw, subtracting the width of our flyover, dividing it by 2, and then using that to set the margin. Surprisingly this worked swimmingly, because I felt like I pulled that idea out of nowhere.

First of, what is vw? It stands for view width and references the width of the viewport. It's brother is vh, which stands for view height but isn't relevant to today's problem.

What is calc()? It is a CSS construct that allows us to make calculations at runtime.

Let's start with some simple HTML:

<html lang="en">
<div class="maindiv">
<h1>Hello You!</h1>

There is an HTML, a body, a div, and some content inside the div. First, I'm going to expand the HTML and body the full height and width of the available viewport:

html, body {
height: 100vh;
width: 100vw;
background-color: grey;
margin: 0;

Do this with CSS, of course.

Now, let's look at the maindiv. I'm going to size it to 50% width, and 100vh height:

.maindiv {
height: 100vh;
width: 50%;
background-color: white;
display: inline-block;

I also gave it a background color of white, to offset it from the background of the full app, and the display is inline-block which means it will accept layout cues from the parent, in this case the body tag.

In order to get the item to center, we'll use calc() with the margin:

margin-left: calc((100vw - 50%)/2);

The calc takes the full 100vw and subtracts 50%, the same width of the maindiv. Then it divides that number in half. The resulting value--calculated at runtime--essentially centers the maindiv on the page:

Play with the same here.

I feel a slight tinge of success when off the cuff ideas like this work elegantly.

How to center a div on a page using CSS?

There are a ton of posts about this topic, so I'm just writing this up in hopes I can remember it for this time. How can you center a div on a page? I'm working on a site that where the design requirements were fixed width. These days with mobile devices, I'm a much bigger fan fluid layouts, but that isn't this project.

So, my application needs to be some width, say 500 pixels, and centered within the screen. This is how I'm gonna do it. First, start with an HTML Page:

<div class="centereddiv">
<h1>Hello You!</h1>

There is an HTML body, with a div inside it, and some more content inside it. First, I'm going to add some CSS for the HTML and Body tags::

html, body {
height: 100vh;
width: 100vw;
background-color: grey;
text-align: center;

This sets the HTML and body tags to the height and width of the viewport area using the vh and vw units. I also gave a grey background and told it to center its contents with text-align: center.

Now add some CSS for the centereddiv:

.centereddiv {
width: 500px;
height: 100vh;
background-color: white;
display: inline-block;
text-align: left;

A width is specified. I used a pixel width, but this should work fine with a percentage width if you wish. The key part is the display being set to inline-block. This is the piece that tells this div to display in-line basd on the rules of the parent, and the parent uses text-align to center children. That is the magic.

I gave this a height of 100vh, and used text-align to left align the body, but neither matters for the purposes of this sample.

Try it out

It works pretty well.

Naming Conventions Up and Down the Stack

I recently had the opportunity to work with a brand new team building a product from scratch. I never realized how unusual this situation is until I was doing it. As a consultant, I am used to dealing with an existing code base, and do not partake in the arguments around coding conventions that occur before we start writing code. I usually step into existing project, learn the conventions quick, and start contributing. This time, I was center to the debate.

This post will focus on naming conventions, covering every piece of the stack, starting with the database, to the services layer, to REST URLs, to front end code conventions.

As the team created our conventions, we kept passing around links to random blog articles from unknown people about the way things should be. While these articles were often interesting to digest, they were always presented as a canon solution, when in fact they were just the opinion of some random guy on the Internet.

I'm writing this so that next time I can be that one random guy on the Internet whose opinion matters more than yours.

The Database

Let's start with the database. A database is the data store behind your application, and the bulk of projects I work on still use Relational databases, so that is my context. I don't have an opinion on NoSQL databases yet.

The Way it Should Be

Table names should be in ProperCase, sometimes called PascalCase. In ProperCase the first letter of a word is in uppercase, while each consecutive letter is in lowercase. For compound word, the first letter of each word should be in caps.

Here is a simple database structure:

Notice that the table names are plural. This is because every table will contain many items. For example, the Users table has many users. Each row represents a single user, but the table, as a whole, represents all users. You can see ProperCase in action in the linking table, UserRoles. The 'U' from User is in uppercase, and the 'R' from Roles is in uppercase, but all other letters are in lowercase.

Column names should be in camelCase. The camelCase syntax is just like ProperCase, except that the first letter is lowercase instead of uppercase. You see this in columns such as firstName and lastName on the Users table.

The columns should be named singularly. We might state this as an entities table contains many entities, and each entity row has a single column. Populate this sentence with real tables from the diagram: A Users table contains many users, and each user row has a single firstName.

Stored Procedures and Views should use ProperCase in their name, because these are top level elements, just like Tables. Triggers or indexes should use camelCase because these are secondary level elements just like column names.

Why Use Something Different?

Overall, the database naming techniques I love are universal in most projects I've worked on. I did run into one situation where we decide to make the table names singular instead of plural. The reason for this is that the ORM we were using on our services layer generated class names based on the database tables, and we wanted our class names singular instead of plural. Some ORMs, such as hibernate allow us to create a mapping between database table and Java class, but others such as JOOQ do not.

The Backend Services

A service layer is built primarily to communicate with the database, but sometimes it can communicate with other services, such as a Facebook or Twitter API for example. How do we apply naming conventions to this server-side code?

The Way it Should Be

Code is put inside files, and for file names I like to use ProperCase, just as I did for table names in the previous section. Class names mirror the file names, but of course do not have an extension. So, a file would contain a User class.

If I were to model the database structure from above as classes, it would look like this:

The Users table parallels a User class. The Roles table parallels a Role class. Each class instance represents a single record from the database table. The intersection table of UserRoles turned into an array of Role objects in the User class, named roles.

The class names are singular. Every class instance represents a single user, or a single role. A User has a firstName, not Users have a firstName. Property names are in camelCase, which again is just like ProperCase but with the first letter in lowercase instead of uppercase. You see the compound word affect with properties such as firstName and lastName, mirroring what we did at the database level.

The plurality of properties depends upon what the role represents. Since a user has many roles, the name of the roles property is plural. But the User can only have one firstName or lastName, so those properties are singular.

I use similar conventions for files that do not mirror database objects. File names and class names are put in ProperCase. Variables and methods on those classes would be in camelCase. You may have a UserUtils class, for example, that contains a special function to check a User's credentials. This method would be in camelCase structure, one example may be isUserInRole().

Why Use Something Different?

This approach has been consistent with most server-side technology I've had to deal with, from Java to PHP to ColdFusion and even back in the Lotus Notes and iCat days (<-- they were real technologies I swear). I have used this same approach with some NodeJS server-side projects. I have seen an alternate naming approach used on some server side NodeJS projects, but I'll discuss that when I talk about UI code and Angular in a bit.

REST Services

A REST service is a way to load data over a URL. The first time I used anything close to a REST service in a browser application, I loaded data in a hidden iFrame and wrote my own JavaScript to process it and redraw it on the screen. Things are different today.

I have seen a lot of morphing of REST services over the past ten years and the best approach seems like a moving target. I do see some convergence in ideas, and some conventions are growing on me as standards. One example is the use of HTTP Verbs to represent the action being performed. For example, GET requests are used for retrieval, POST requests are used for creation, and PUT Requests perform updates. I'm digressing. The use of these transport mechanisms are unrelated to naming conventions of the REST URLs.

The Way it Should Be

The server name, or domain name, of a URL is never case sensitive in a URL, but the rest of the URL might be, depending on the server implementation. The URL should contain the element being interacted with. Let's look at a sample URL to load all users:

After the domain name, we have the element which is being acted on, in this case Users. A request here would process all users, most likely a GET request would return users. I specifically used ProperCase in the URL to represent Users, and this mirrors how we named the data in the services layer and the data layer. Notice I made users plural, because this request processes all Users.

To update a single user, I recommend creating a singular endpoint:

This processes a single User. A POST request would create a new User, and I would expect the body of the request to include a JSON payload representing the new user's data.

A GET request would load a single user, most likely with a URL variable, to specify which user to load, probably like this:

Would load the User with a userID of 1. A PUT request to the same URL endpoint would update the user with a userID of 1, based on the JSON payload represented in the body.

Why Use Something Different?

I like to make the element in the URL singular if it is operating on a single element, or plural if it is operating on multiple elements. This makes logical sense to me. However, I've seen the argument that the URL should always be plural. A URL like this:

Means you are operating on the Users collection where the userID is 1. A PUT would update that User where userID is 1, and a GET would retrieve that User where the userID is 1. I personally feel this approach is less self-explanatory when reading a URL. It makes me think too much.

However, one benefit to this approach is that you'll implement all the HTTP verbs for the same endpoint. When separating out operations on a lot of Users and a single User, it is unlikely I'd implement a PUT or POST request at the Users endpoint, because we will not be creating or updating multiple users in one call. Not having two similar endpoints, with different plurals, makes the programmer need to think less about which end point they need to access and that is a positive good.

Either approach is fine as long as the documentation is there to support it and guide your REST consumers.

User Interfaces

For most of what I do today, the User Interface code includes HTML Templates, JavaScript or TypeScript files, and CSS Files. I haven't done enough mobile development, or desktop application development to have developed a strong pattern about naming conventions in those areas.

The Way it Should Be

When writing UI code, such as JavaScript my first impulse is to model the same structure that I use in the service side. File names and class names follow the ProperCase convention. Variables and methods inside a class use camelCase. I like my UI code side conventions to mirror the server-side conventions as much as possible.

Why Use Something Different?

I have been doing a lot of Angular development as of late. When doing Angular it makes a lot of sense to use the Angular CLI, and the Angular CLI uses a file naming convention called spinal-case. Everything is in lowercase, and compound words are separated by dashes. A class might be something like this:


The class inside that file would still be named UserRole, so class names are left untouched. Angular components are split up into multiple files: a CSS File, a Test File, a HTML Template file, and a spec file. The Angular CLI also specifies the type of file as part of the file name, .components for components. Creating an Angular component will give you this:

  • user.component.css
  • user.component.html
  • user.component.spec.ts
  • user.component.ts

The class inside the user.component.ts will be UserComponent. Angular uses a similar approach when creating a service, replacing the .component with .service in the file name. Services also do not have CSS or HTML files associated with them.

When building Angular applications, I recommend you use the conventions laid out by the Angular CLI, even if they may be different than guidelines on other aspects of your stack. File names aside, I still use camelCase for functions and variables that are created as part of a class.


I wanted to talk about Acronyms, ID fields, and constants a bit, because they are areas where things can digress.


There are two common approaches I've seen to using Acronyms within a database table, class name, variable or method. The first is to put it in all caps, this is my preferred approach. In real world text, acronyms are written in all caps, and our code should mirror that approach. Let's use the acronym TLA--Three Letter Acronym--as a sample.

You might name a class like UserTLA, a variable like this userTLA, and a file name like this UserTLA.extension. If the acronym comes at the beginning instead of the end, I'd name a class like TLAUser, a variable like TLAUser, and a file like TLAUser.extension. This breaks other conventions for the variable name, so you might call it tlaUser, but that is never my preference.

The second approach is to cap the first letter and lowercase the rest. You might name a class like UserTla, a variable like this userTla, and a file name like this UserTla.extension. If the acronym comes at the beginning instead of the end, I'd name a class like TlaUser, a variable like TlaUser, and a file like TlaUser.extension. For variable names, this also breaks the convention of lower casing the first letter of the variable, so sometimes I'll see something like tlaUser. I'm not a fan of using any lowercase in acronyms. Although it may offer more consistency across the code base, than putting the acronym in all caps, it still forces my brain to think harder when reviewing code.

ID fields

An ID field is a special case. ID is not necessarily an acronym, it is more of an abbreviation for identifier. It is common in the database to add the ID postfix to the column that uniquely represents a record--we call this the primary key. I prefer to put ID in all caps, such as userID. Others prefer to capitalize the I and lowercase the D, such as userId. A recent project is using the second convention, lower casing the `d`. It has taken me 6 months, but I've started to reverse the muscle memory I've built up over the years.


Constants are just like variables in code, but the intent is that they never change. To distinguish constants from regular variables, I often see them created with all caps. For compound words, I separate them with an underscore. A constant might be created like this:


An underscore separates multiple words, and this process can be called Snake_Case. This approach seems pretty universal in all technology I have worked with, but I've never seen it required.

Final Thoughts

I want to leave off with this quote from the Google Style Guide:

"Every major open-source project has its own style guide: a set of conventions (sometimes arbitrary) about how to write code for that project. It is much easier to understand a large codebase when all the code in it is in a consistent style."

The emphasis is mine. Conventions are arbitrary. At the end of the day, the naming conventions you use on your project do not matter. I like to encourage consistency because that it makes it easier to maintain the code base, for yourself, your future self, and your replacement. But the actual choices you make are more a matter of personal preference than anything else.

More Reading

How to fix the "definition not supported by current JavaScript version" error in IntelliJ

I put together this screencast to show you how to fix the 'not supported' error in IntelliJ that I often see when creating new projects.

More Entries

All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version