Lesson 5 – Data binding and variables

In this next section we actually get down to creating our application in a more fleshed out version rather than just creating a “hello world!”

Remember that my goal is a tutorial and Q&A website so Bucky’s steps are in line with mine – he wants to create a video file list and so do I so, for the moment, I’ll just be following his lead. As I get further into the project I might begin to deviate from his strict code as I implement features that I need that are different from his needs.

So back to the code.

In this video Bucky introduces us to variables. Instead of simply specifying text in the component template (@component ({template: “xxx”});) we’re going to be setting this to a variable defined elsewhere (specifically in the component class that we created in lesson 3 in the app.component.ts file). In the component class we’re going to add a variable name followed by an initializer (I’m using the text “Virtual Diploma” as this is the name of my expected, final product) like so:

export class AppComponent {
    heading = “Virtual Diploma”;
}// AppComponent;

Now, a couple of points here where I deviate from Bucky. First of all, I didn’t like the convention

<component_name>.component.ts

Why? Because if you have a whole bunch of these (and you will) then your components get all mixed up with your other code files when the file list is sorted (which Visual Studio does automatically and so does WebStorm by the look of the video). So, instead I’m going to prefix my component files with “component”, like so:

component.<component_name>.ts

That way all of the component files will be grouped together. The other place where I do things differently is that I always add a comment to my closing brace which corresponds to the command of the opening brace. Notice how I’ve added:

//AppComponent

to my closing brace? That way if the opening brace and the closing brace encapsulate code that is more than a screenful then I don’t have to scroll up to see what the closing brace is closing. It is also useful for detecting extraneous braces, both of which happen quite frequently.

Anyway, to continue.

The variable that we’ve created in the component class can now be used in the component template. Where we had:

@Component({
    selector: ‘my-app’,
    templateUrl: ‘<h1>Virtual Diploma</h1>’,
})// Component;

we replace it with:

@Component({
    selector: ‘my-app’,
    templateUrl: ‘<h1>{{ heading }}</h1>’,
})// Component;

Whenever variables are used in a template they’re surrounded by two sets of braces nested together as shown above. I’ve opted to include a space before and after (forget what I said about spaces inside parentheses, here – this is different and I think it makes it more readable) but from my experience it doesn’t seem to matter. You can leave these out if you like.

Now, in this situation, where the variable is used only once this will suffice, however, there will be situations where you want to use the same variables in different parts of your program or globally. In order to do this I’m going to set up a separate global class in which I’ll put my title as a static variable or constant (“static variable” is a contradiction because once a value is static, it’s not variable anymore).

So, I’ll create another class and I’m going to deviate from Bucky again, here. I’m going to call my file config.settings.ts (Bucky calls his config.service.ts). I’m going to call my class Config, too and, in it I’m just going to put my constant for the header (called main_header). It uses the keyword static, has a type definition and  looks like this:

export class Config {
    static main_heading: string = “Virtual Diploma”;
}// Config;

Very simple. Now I can use this class in my components.app.ts file. I’ll set my class variable for heading in the AppComponent class to this value and then, when the page is called the template will bind to this value:

export class AppComponent {
    heading = Config.main_heading;
}// AppComponent;

In order for the components.app.ts file to get access to this constant I’ll need to add an imports directive to my file, just like the one I added to include the Component class from the A2 library:

import {Config} from “./config.settings”;

Now, when I need to change the title (which I will have used all over the place and when someone presents me with a cease and desist order for copyright infringement – I don’t know if there’s already a “Virtual Diploma” out there but I wouldn’t be surprised – for example, then I don’t have to change it everywhere in my program – I just change it here and it will be reflected everywhere.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Lesson 4 – The main component and component loading

The first file that Angular 2 loads is main.ts which is defined in the script contained in the HTML file (in the System.import command – it is the only parameter). This can really be called anything and can live anywhere but, for my purposes (and Bucky’s) I’ve put it in the typescript folder under the app folder (which, also can be called anything but “app” seems to be the convention so I’ll go with it).

The main.ts file contains a single command (along with a couple of import references, notably to the component that we created in Lesson 3 and to the Angular 2 core library, itself):

bootstrap (AppComponent)

See the code

where AppComponent is the name of the component that we exported in the component file. Again, this can be called anything, so long as it’s consistent but, as this is the main application component AppComponent seems like an apt name.

A quick note, here. Those of you who are familiar with my coding practices in the past (and I doubt any of you are) I’m a bigger fan of the underscore ideology over mixed-case when it comes to naming things in code. I’m a big fan of readability in code (and a lot of that will come across as I develop this application) and I don’t think that mixed-case is very readable. YouWouldThinkIWasCrazyIfIStartedWritingLikeThis in this journal but if_I_wrote_like_this it would be much easier to read. Well, 99% of the programming community disagrees with me so, with a few exceptions, I’ll be using the mixed-case convention, here.

Another place where I disagree with the programming community at large has to do with the placement of parentheses. I prefer to have a space before them whereas most programmers(and especially the ones who blog a lot)prefer to not have spaces. Well, this is just outright poor writing. Even worse, some programmers put spaces after the opening parenthesis and before the closing one( like this )which is crazy!

Anyway, back to the code.

The two import directives included in the video import two different things: the first one imports the bootstrap module (not to be confused with “bootstrap” the css framework which I’ll work my way through in a later series) which loads up the main application component.

The second is a reference to the AppComponent that we created in Lesson 3. Bucky makes a good point, here. Anything from the Angular 2 library (I’m tired of writing “Angular 2” every time I need to so I’m going to call it A2 from now on) does not have any pathing – it defaults to the node_modules folder. Our own references need to be pathed (using “./” if they’re in the same folder as the component that’s calling it). Forgetting this tidbit is not recommended.

In the HTML file (index.html) the script tags are added. Bucky’s version has more than the version provided by Ibrahim – I don’t know which ones we’ll be using but in keeping with “keep it simple” I’m using Ibrahim’s references. As some point I’ll chop a few out and see where it falls down so that I can get an even more concise listing.

SystemJS:

This is a script command (System.config) that includes a module loader (SystemJS) which automatically loads our JavaScript files without us having to individually list each one in its own <script></script> tags. This is the main stumbling block I came across when I was trying to create an MVC version. My post on Stack Overflow details this problem – I still haven’t figured it out the solution so if anyone has a suggestion then please let me know. For the moment I’ve decided to scratch the MVC version in favour of the flat, file based model that we all know and love from the early (pre-MVC) days of web development, but I would like to get this solved at some point and will get back to you on that one.

Update: a solution has been posted but I still can’t seem to get it working (I think the solution provider is on the right track so I’ll give it another shot and will back back to you).

Anyway, the packages attributes tells SystemJS (the package loader) what to do when a new package is requested. This includes a defaultExtension which specifies an extension to use for requested files. Because of this, whenever a file is referred to in an import component (by the way, I use the term “component” and “directive” interchangeably when referring to these “components” but “component” is the correct term) the file extension is not included because SystemJS fills it in from this command.

There’s no explanation for the “format” property in Bucky’s presentation. Maybe he’ll get to that later. If not then it’s probably not to hard to find a description.

Finally, there’s a System.import command which is simply the starting point, telling A2 which file to load first (in our case app/javascript/main.js).

See the code

 

 

Lesson 3 – Components

Components are the basic building blocks of an Angular 2 application. This is where we start actually building the application.

1. The Component object needs to be imported. That is done with an import command, like so:

import {Component} from “angular2/core”;

2. A component is defined with the @Component ({}) command. It’s called a “decorator”. There may be other decorators (I don’t know, yet).

3. A component has a selector directive, which is the name of the tag that you’re going to use in the HTML code. It tells Angular 2 where to put the stuff that it’s going to create.

4. In its most basic form, a component also includes a template which is the actual code to replace the selector contents with. In this video Bucky uses as string with HTML in it. There’s a better way which he talks about in a later video.

Something to note – the selector tags are not removed. Only their contents so they will stay in the resulting HTML code.

5. The components file has an export component which he talks about in more detail in a later video. The export class is public and can be included in other files.

6. As I mentioned in my introduction, the existing contents of the selector tags display until the application is loaded. This is useful for a “Loading” screen.

 

Lesson 2 – What the files do

This second video shows what all of the files in the Angular 2 application do and what they are for. Here are the highlights:

  1. This lesson gives us a brief rundown of TypeScript which I already mentioned in a previous post. If you’re using Visual Studio then you don’t have to worry about this much because Visual Studio has a built-in TypeScript transpiler.
  2. All of the Angular 2 program files are contained in the app directory. Bucky has two subdirectories called js and ts, respectively (I used the full names: javascript and typescript). The directory naming becomes more important as I get further into the development. More on that, later.
  3. Don’t mess with the files in the js (javascript) folder. They’re generated automatically (by your development environment).
  4. Map files provide a roadmap between the JavaScript and TypeScript files, used for debugging. Bucky didn’t tell us exactly how that works but I’m hoping that he will get to it.
  5. The node_modules folder contains the files that were downloaded by npm or Visual Studio (depending on your download method). Again, don’t mess with them. They “just work”. Actually, here’s another thing that I discovered – when using Visual Studio don’t actually include them in your project, either! If you do then Visual Studio will attempt to transpile them and that can lead to a myriad of headaches. They don’t need transpiling as they’re already converted to JavaScript.
  6. The typings folder contains rules to translate TypeScript to JavaScript. My project doesn’t use it so maybe it will be important, later. The point being that it doesn’t seem to be immediately necessary. Apart from the rule of development that Bucky and I seem to agree on “never repeat yourself”, I add the philosophy of “keep it simple” so the more stuff I can not include the better.
  7. The .gitignore file is used by Git for publishing. Files and directories listed in this file are not published. Again, not relevant to my purposes unless I intend to publish my source code (which I don’t).
  8. index.html is self-explanatory. In my attempts to make an MVC version this would be the view (or layout page if I ever get that far).
  9. package.json is a JSON file that contains the files to download and include. I mentioned this in an earlier post.
  10. README.md – this is another Git specific file and is the text that’s included on Git when the files are uploaded. Again, not relevant to my purposes.
  11. tsconfig.json – I took Bucky’s and used it for the purpose of separating my TypeScript files from the JavaScript files into their respective typescript and javascript folders (which Visual Studio respects, which is handy). If you don’t care about this then this file is dispensable. Bucky only talks about this functionality. The rest might become important, later.
  12. typings.json – Like the packages.json file, it defines what to include in the Typings directory which we don’t use.

 

 

 

 

 

 

 

 

Lesson 1 – Setup (Bucky’s way)

Most of what is covered in this video is stuff that I’ve already talked about in my “Setting up the environment” post so I’ll just gloss over the untouched points:

  1. NodeJS is a requirement. Well, not the server, itself (I’ll write about that later – the concept is pretty cool – writing server-side JavaScript) but for the npm repository tool. I didn’t use it – I used the technique that I spoke about in the previous chapter but for those who aren’t using Visual Studio, this is required.
  2. If you’re not using Visual Studio then you can get a sample project from Bucky’s GitHub account to use as a starting point.
  3. package.json contains a list of the dependency files. You can use npm to download them, from the command with:npm install

    which will find the appropriate files and will download them. Or you can use my technique which I mentioned in the previous post.

Setting up the environment

Before I can write any Angular 2 code I need to set up a development environment. Bucky recommends using WebStorm but, quite frankly, it’s a) out of my price range and b) I just prefer to use the Visual Studio environment. So I’m going to set up an Angular 2 project using Visual Studio. Now, this task isn’t as simple as it sounds. I spent a lot of time trying to get it all up and running and what I found was that it’s really not as easy as it looks.

That was until I came across this post by Ibrahim Uludag. It shows a nice, easy way to get started using Visual Studio. I then spent a bit of time trying to get it running using MVC. I was unsuccessful. I’ll update you on progress when (if?) I ever get back to it.

So, I went ahead and just used Ibraham’s method and I was up and running in a few minutes, but with two caveats:

1. You will most likely encounter an error. It goes like this:

error TS2661: Build: Cannot re-export name that is not defined in the module

After a quick googling I found that this is a common problem and the solution is equally as simple (thanks to sicaner on GitHub for providing it):

In the file node_modules/angular2/src/façade/promise.d.ts add the following line to the beginning of the file:

declare var Promise: PromiseConstructor;

This took care of it for me.

2. Unlike Bucky’s environment which automatically retranspiles the TypeScript code, the Visual Studio environment only transpiles when the application is started. Therefore, whenever you make a change to your TypeScript file you need to restart the application in order to generate the new JavaScript files.

Another thing to note is that you can shortcut Ibrahim’s method of getting the Angular 2 libraries by right-clicking on the packages.json file and selecting “Restore Packages”. I found this much easier than his method and it still has the same effect (this is assuming that you’re using Visual Studio 2015 Community Edition, which I am).

Also, a quick note on TypeScript. You can find out plenty about TypeScript with a Google search but just be aware that Angular 2, unlike AngularJS (or Angular 1) is built on top of TypeScript whereas AngularJS was built on top of JQuery (I think – correct me if I’m wrong). Therefore, learning a little about TypeScript is rather important.

Here’s a quick overview: TypeScript, developed by Microsoft, is a language which, when transpiled, gets converted into raw JavaScript (browsers only understand JavaScript). Note that it is “transpiled” and not “compiled.” “Compiled” means to turn it into machine language. “Transpiled” means it gets converted into another language which is then “interpreted” on the client’s machine into instructions that the computer can understand.

TypeScript allows the user to write code using traditional Object-Oriented techniques instead of the more cryptic Prototype ideology that JavaScript employs.

Now, something you might encounter is that your changes don’t look like they’re being applied. This is most likely because of the browser cache – when the TypeScript is transpiled it creates a JavaScript file. Your browser looks at the file and says to itself “oh, I already have that file – I don’t need it” so it won’t get the most recently transpiled version. To prevent this, disable your browser’s cache.

Next, let’s go through Bucky’s lessons, one by one.

See the code

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Introduction

In my quest to keep up with the latest technologies I’m now learning the next wave in web application development – Angular 2. The purpose of this journal is to document everything I learn as I learn it, partially so that I will have a reference to return to if I get lost or forget something but also so that other people can learn from my experience and avoid the mistakes that I make as I go along.

In creating my first Angular 2 application I’m following the tutorials by Bucky Roberts at The New Boston located here. The purpose of the first project is pretty simple: to create a web application that displays video tutorials (similar to what Bucky is doing) but also to add a series of questions after each video so that the viewer can test how much they’ve absorbed in each tutorial session. The first one, naturally, is on Bucky’s Angular 2 tutorial, itself.

I just want to add a quick note, here. When I first heard about Angular (Angular 1 or AngularJS) my first thought was “are they crazy?” Creating an entire website on the client via JavaScript was not my idea of a rational thing to do as it relies on the user having a machine that is capable of handling it. Well, I’ve since changed by mind. First of all, if a person doesn’t have a computer that’s capable of handling it then they need to get into the 21st century.

And, secondly, I like the “Loading” functionality. Any complex website will present the user with a blank page until such time as the content loads. By creating the page client-side, you can have a brief “Loading” message that will display until the application is ready for presentation. Furthermore, even the library loading will be quicker if you use a CDN (content delivery network) because if they’ve visited any other Angular 2 website then they will already have the necessary files.

Anyway, enough on that. I’ll publish the work as I go along but for the moment this blog is all text. It’s a work in progress so check back, often.