Lesson 8 – Passing data to components

In this lesson we’re going to look at how to pass the array of lessons that we created in the last lesson into the LessonComponent so that they can be used in the template markup and, thus, shown to the screen. In order to do this we use a technique known as “Attribute Binding” which, to quote Bucky, is how to send data from one component to another.

In the main component html, I’m going to add a new tag called lessons in which I’ll add a new property. The property name is encased in brackets. The value of this property is going to be the name of name of the class variable you want to use – in our case it’s going to be the lessons variable that I included in my AppComponent class which, if you’ll recall, is an array of lessons. So it will look like this:

<h1>{{ heading }}</h1>
<lessons [lessons]=”lessons”></lessons>

To avoid confusion I think I’ll rename my tag from lessons to course (if you’re following along with the video, this is the equivalent to Bucky’s playlist). To do that I’ll change it here in the HTML and also in the selector in component.lesson.ts.

Now here I found a problem. Bucky claims that you can set the name of the property in the tag to whatever you like but I found that doing so breaks the code. Initially, I tried to change the property name from “lessons” to “lesson_list” as this seemed more mnemonic, like so:

<course [lesson_list]=”lessons”></course>

But I found that this doesn’t work. The name of the property has to be the same as the name of the variable that you’re using so it must be:

<course [lessons]=”lessons”></course>

If anyone can tell me I’m wrong I’d love to hear it – please leave a comment in the comments section, below.

I think I’m also going to change the name of my LessonComponent to CourseComponent (and, respectively, its filename to component.course.ts and its corresponding HTML file to component.course.html) so that this distinction between courses and lessons is made more clear. Don’t forget to change the name in the import statement in the app component, too, as well as the directive statement in the AppComponent @Component statement (called a “decorator”).

While I’m at it, why don’t we just go ahead and change the decorator’s selector name from my-app to something more meaningful? I’ll call it “virtual-diploma” so that we know that this is the main app tag (corresponding with the name of the application). I’ll change it in the decorator in component.app.ts as well as in the main index.html file where it is used as an HTML tag.

Now, why am I doing all of this name changing? Apart from the fact that these names become jumbled as the application becomes more complex (in a strict development environment it’s wise to carefully consider the names before using them), repetition is the key to learning. By changing these names it forces me to go back over what I’ve already created to make sure I understand what correlates with what.

Anyway, to continue.

In my HTML file for the course (component.course.html) I’m going to create my list of the lessons in the course. It’s a simple table, just like Bucky’s, with the ID, the title and the description. ID will become arbitrary when auto-increment is implemented so I’ll probably add another ID field that is a populated incremental number of the lesson index (first lesson is “1”, second is “2” and so on) but for the moment I’ll just use the ID as entered in the array.

So, it’s a simple table like Bucky’s (without the Bootstrap – I’ll deal with that in a separate series) and looks like this:


The part where the ellipsis appears is going to be where I put a loop in order to iterate over all of my array items and give each one its own row. So, in the <tr> tag I’m going to add a new property – a predefined A2 property called *ngFor which acts like a for statement in other languages. The value of this is going to be an item identifier and the array that we’re getting the values from. I’m going to use my favorite “item” for each line item. The resulting table row tag is going to look like this:

<tr *ngFor=”#item of lessons”>

Note the hash character (#) in front of my item variable – this is the syntax for declaring the for variable in A2 (and may be used in other places as well – I don’t know). Now, for each of those items I’m going to list the ID (the lesson ID), title and description in table cells, corresponding with the table header that I wrote earlier. Each property will be prefixed with the item variable followed by a period followed by the property name. As I’m outputting variables I’m going to use the same data binding syntax that I used with the application header (i.e. two nested sets of braces):

<tr *ngFor=”#item of lessons”>
     <td>{{ item.lesson_id }}</td>
     <td>{{ item.title }}</td>
     <td>{{ item.description }}</td>

Now, when I restart my application I see each of the data items listed in the array created in the component.app.ts class listed as separate items in my table.











Lesson 7 – Nested Components

At this point we have a pretty good framework. The next step is to include the LessonComponent into the main AppComponent. The reasoning for this should be pretty obvious but let’s spell it out. When the application is run there’s only the one component included in our main index.html file and that is the my-app component (designated by the <my-app></my-app> tags). Of course I’ll change the name of this to something more meaningful later on but that’s where we are, now.

In order for the LessonComponent to be included I have to add it somewhere. So, in order to do this, I’m going to import the LessonComponent into my AppComponent by adding

import {Video} from “./data.video”;
import {LessonComponent} from “./component.lesson”;

to the components.app.ts file. I’m also adding the Video class component as I’ll need it, later. In addition, to actually include it in the AppComponent, in the AppComponent @Component definition as a new property definition called directives.

@Component ({
    selector: ‘my-app’,
    templateUrl: ‘app/markup/component.app.html’,
    directives: [LessonComponent]
})// Component;

Sharp eyes will also noticed that I’ve spun off the markup into its own HTML file which I’ve put under the markup folder and called component.app.html, in order to stay consistent. It should also be noted, as Bucky points out, that the bindings are still legitimate in the templates so the component.app.html file still includes the heading variable surrounded by two pairs of braces.

Also note that directives are encapsulated by braces, essentially making them an array. Now I’m going to set up my list of videos and I’m going to do that by extending my AppComponent class. I’ll add a new variable which I’ll call lessons which will be an array of the video class that I created earlier. Actually, I’ve gone ahead and changed the Video class to a Lesson class and have renamed the file accordingly (data.lesson.ts). Again, I’m going to initialize it to null – values will be set in the constructor.

lessons: Array<Lesson> = null;

I’ll also add code to the AppComponent constructor to populate this array. For the moment I’m just going to include the first two of Bucky’s tutorials and I’m going to hard code them. Later I’ll change them to read from another source (a database).

    constructor () {
        this.lessons = [
            new Lesson (1, 1, “Lesson 1”, “hXfigUyeHaY”, “First lesson in Bucky’s Angular 2 for Beginners series”),
            new Lesson (2, 1, “Lesson 2”, “vc9n0j6-D2U”, “Second lesson in Bucky’s Angular 2 for Beginners series”)
        ]/* this.videos */;
    }// constructor;

This creates an array and each item in the array is one of the Lesson class objects. I’ve manually numbered them – the first parameter is the lesson number (lesson_id) and the second is the course number (course_id). Because they’re all part of the same course and it’s currently the only one I have they are both course number 1. Later on when I have code to add new lessons these IDs will be populated automatically by the database in an auto-increment field but, for the moment, I’ve just added them manually.









Lesson 6 – Creating our first component

In this video we’re expanding on the knowledge that we’ve already received in the previous lessons. In this section, again following Bucky’s lead, I’m going to create a class that contains the video titles. At some point in the future I’ll expand on this class to include the testing portion and, most likely, read the values from a database because I’ll also want to create an administration CMS (Content Management System) that will allow me to create other lessons without having to hard-code them in the A2 program.

Besides making the program more dynamic, it also allows for a separation of concerns, where the code is separate from the data and is also separate from the markup, which I love and Bucky mentions, later.

I’m going to start by creating a new class which I’ll call videos and will put into a file called data.video.ts. Again, I’m putting the type of class at the front of the name in case I have other “data” type classes so that they’ll all be listed together. Like Bucky, I will include an ID, a video code, a title and a description. These will be my eventual fields in the database. But, here again, I’m going to deviate a little bit. My eventual application will include several courses with several sets of videos and assessments. Therefore, I’m going to have two ID fields: one for the the lesson (instead of “video”) and one for the course. I’ll name these lesson_id and course_id, respectively.

These simply get listed in the class, name followed by colon followed by type, but since none of the values get filled in Bucky opts to leave it at that. In keeping with my methodology, I’m going to explicitly set them to null (meaning “no value”). I’m also going to set an access modifier on them all – eventually, I won’t want them to be publicly accessed but for the moment I’m going to set them all to public.

The resulting class looks like this (including a constructor):

export class Video {

public lesson_id: number = null;
public course_id: number = null;
public title: string = null;
public video_code: string = null;
public description: string = null;

constructor (lesson_id: number, course_id: number, title: string, video_code: string, description: string) {

this.lesson_id = lesson_id;
this.course_id = course_id;
this.title = title;
this.video_code = video_code;
this.description = description;

}// Constructor;

}// Video;

Now, having created the class, I’m going to need a component to display that information, and the information is for our lessons, so I’ll create a new component file called “component.lessons.ts”. This will include the information needed to display each of the lessons (and, eventually, the videos and quiz questions).

This component, of course, needs the A2 core library so I’ll include the import statement (like I did in the app component) and will include a @component statement. It will have a selector which I’ll call lessons. At this point, however, we introduce something new: the concept of code and markup separation which I alluded to earlier. Rather than having all of our markup code in the template property (which could easily get out of hand) I’m going to use the templateUrl property, instead.

This property allows us to include a URL instead of a template string which will let me put the HTML in a separate file. Also, Bucky points out that in order for this to work you need to have a full path so I’m going to capitalize on this feature and I’m going to create a new folder under my app folder which I’m going to call markup. This way I can keep my JavaScript files separate from my TypeScript files separate from my HTML files. Like Bucky I’m going to use the same filename but with an HTML extension: app/markup/component.lessons.html.

Of course I’ll need to export the class by giving it a name (like I did with the component.app.ts file) and I’ll call my class LessonComponent.

export class LessonComponent {}

It’s empty but that’s fine for now. I’ll populate it in the next lesson.













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


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:


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:


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:

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

we replace it with:

    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.


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
















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.