Explore Free TypeScript & Angular Tutorials – GameDev Academy https://gamedevacademy.org Tutorials on Game Development, Unity, Phaser and HTML5 Thu, 23 Feb 2023 21:14:36 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.1 https://gamedevacademy.org/wp-content/uploads/2015/09/cropped-GDA_logofinal_2015-h70-32x32.png Explore Free TypeScript & Angular Tutorials – GameDev Academy https://gamedevacademy.org 32 32 An Introduction to TypeScript https://gamedevacademy.org/typescript-tutorial/ Fri, 18 Jan 2019 22:30:53 +0000 https://html5hive.org/?p=2022 Read more]]>

You can access the full course here: TypeScript for Beginners

Part 1

In this course, we’re going to learn the ins and outs of TypeScript.

About TypeScript

TypeScript is a superset of Javascript.  This means that while Javascript is valid TypeScript, TypeScript is not valid Javascript and has to be transpiled to be compatible with browsers.  However, TypeScript offers numerous benefits like IntelliSense and other features that help catch code errors.

Downloading Necessary Programs

We’ll first begin by downloading and installing necessary programs for this course.  Head over to the node.js website (https://nodejs.org/en/) to grab the first program.  Select the “LTS” option to download it while making sure you get it for the right operating system.  Once downloaded, double click the download to install it.

Node.js homepage with 8.11.1 LTS version

Next, we need to install TypeScript.  Since node.js comes with npm, or node package manager, we can install it via Terminal on Mac or Command Prompt on Windows.  You can find the code you need on the TypeScript website (https://www.typescriptlang.org/) in the download section.

TypeScript command prompt install instructions on website

Once you have the code, open Terminal or Command Prompt.  Paste the code in and hit enter to install the package.

npm install -g typescript

Last but not least, we need to grab a code editor.  For this course, we’ll be using Visual Studio Code.  On the website (https://code.visualstudio.com/), hit the download button for the appropriate version for your operating system.  Then, double click the downloaded file to install it.

Visual Studio Code homepage with Download button circled

In the next lesson, we’ll start working with TypeScript.

Part 2

In this lesson, we’re going to start working with TypeScript in our code editor.

Finishing Setup

Open up Visual Studio Code if you haven’t already.  Before making any files, we need to install an extension for TypeScript.  On the left column in Visual Studio Code, you can bring up the extensions list via the last item in the column.  Type in “Typescript” to find available extensions and install TypeScript Hero.

TypeScript Hero extension in VS Code

Once installed, head back into the home file area of of Visual Studio Code.  In the Code dropdown area, select the paper icon to create a new file.  You may also right click to create the file.  We will name this file main.ts.  Make sure to put any coding you write along with us in this file.

VS Code with arrow pointing to New File button

About Variables

While in Javascript the standard is to use var to declare variables, in TypeScript we want to use let and const. This is largely due to the scope.  While var is scoped to the function, let is scoped to the code block making it less hazardous.  Const, as the root implies, is a variable that is read-only, thus protecting the variable from change.

export {};

var a = 10;
let b = 10;
const c = 10;

(Note: For now, we need to add export at the beginning of the file to prevent the program from throwing errors.)

With TypeScript, we also assign data types that the variable can accept.  For example, in the code below we specify d can accept a number.  However, by trying to assign a string to the variable, we’re told this is incompatible.

export {}

let d: number;

d = 'hello';

main.ts showing data type error

For the data type, we can declare it as a number, string, boolean, or any. Any is used when the expected value is an unknown type.  Regardless of type, this feature is beneficial for catching certain errors with variable assignment.

Quickly, another feature of TypeScript comes with strings.  With strings, we can use backticks to put our string onto multiple lines.

b = `
    Hello World
    From a multiline!
`;

Transpiling

Let’s try out transpiling our code.  Back in Terminal or Command Prompt, we can enter the following line (which you can find partly from the TypeScript website: https://www.typescriptlang.org/) to transpile our main.ts file.

tsc --target ES2016 ./main.ts --watch

Back in Visual Studio Code, you will see that we now have another file that’s in Javascript.

VS Code showing main.js and main.ts

You can also leave off the target portion of the command, which automatically converts the code via ES5.

main.js as it appears after being transpiled from TypeScript

All in all, TypeScript offers us easy to use and convenient features we can utilize.  Next lesson, we’ll talk more about variables.  If you’d like to learn more about the basic declarations, though, you can check out the TypeScript documentation for them: https://www.typescriptlang.org/docs/handbook/variable-declarations.html

Part 3

In this lesson, we’re going to work on more advanced types of variables in TypeScript.

Arrays & Tuples

We’ll first take a look at an array.  Like other variables, we can assign the array a type so that it checks to make sure additions to it suit that type.  In the example below, while the syntax is different, the two arrays are functionally the same.

export {};

let stringArr: string[];
stringArr = ['hello', 'world'];

let genericArr: Array<string>;
genericArr = ['hey', 'hello'];

By transpiling the code, you can see both arrays are changed to the same syntax in Javascript.

Transpiled arrays from TypeScript showing same in JavaScript

Let’s say you needed an array like object that could allow for all sorts of data types.  For this, we can use tuples.  In tuples, we can specify multiple types it can accept.

let myTuple: [number, boolean];
myTuple = [3, true];

To learn more about arrays and tuples, please refer to the TypeScript documentation: https://www.typescriptlang.org/docs/handbook/basic-types.html

Enumerators

TypeScript also allows for enums, which let us declare our own data types.  For our example, we’ll declare valid types of colors.  When we don’t assign our types values in our enum, we can still use numerical values that will read the index.  A value of 0 would be read as Colors.Red.

enum Colors {Red, Blue, Green};
let color: Colors;

color = 0;

However, by assigning values to our enum data types, numerical values can no longer be used and the direct call of the data type must be used.

enum Colors {Red = 'red', Blue = 'blue', Green = 'green'};
let color: Colors;

color = Colors.Red;

At the bottom of this file you can add the following line to print the color to the console.

console.log(color);

To see it in action, first go to Terminal or Command Prompt again and transpile the code.

tsc ./main.ts

After, you can type in the following, where you should see one of your colors appear as the reply.

node main.js

Terminal showing node running main.js file

Like earlier, you can find more information about enums in the documentation for TypeScript: https://www.typescriptlang.org/docs/handbook/enums.html

In the next lesson, we’ll start learning how functions work in TypeScript.

 

Transcript 1

Hi everybody, my name is Bryce Airs and I’ll be taking you through TypeScript today. So, TypeScript is a super set of JavaScript meaning that JavaScript is valid TypeScript, however TypeScript is not valid JavaScript.

So TypeScript has to be transpiled into JavaScript in order for it to be compatible and run on various browsers. But it does some very important things for us and it gives us type safety as well as gives us Intellisense, meaning, as you can kind of see here, as you start typing it automatically will bring up and try to autocomplete what it is you’re typing which can be very beneficial. Helps prevent a lot of typos and errors and such. So, let’s go ahead to get started, let’s go over to Node.js.org and here you will see two different downloads you can get. I’m on a Mac, if you’re on Windows it probably says Windows there or Linux. But go ahead and select the one that says LTS, long term support, this is going to be, not the most recent, but it’s the most stable.

So go ahead and click on that to download, that will download to your computer, then once it’s downloaded just double click to install. Then, from there, you need to install TypeScript. So after you install Node you should have NPM available, which NPM is a Node Packet Manager. So from here you could download this, but we’ll actually go to the quick start. Excuse me, not the quick start. Here you can see if you’re launching it using TypeScript with various things. On a future video tutorial I’ll be using Angular and Angular CLI specifically which will automatically transpile your TypeScript into JavaScript.

Let’s go to the documentation here, actually download. So if you click on the download link, and this is over at typescriptlang.org then click on the download link and you’ll see this NPM install. So you can take this, oops, there we go. And control c, or command c on Mac, and we come over to our terminal and you can paste that in. And that will go ahead and install TypeScript. So now if you type which tsc, if you’re on Windows it’s probably a different command, to figure out where it’s located. But great, so it shows we have it installed. So now we can run this TSC command, now we’ll go ahead and transpile our code for us, which is super handy. So next we need an editor.

So the editor I recommend is Visual Studio Code. It has great support for TypeScript, there’s a big button here, download for Mac. Probably says download for Windows, or Linux, et cetera.

So go ahead and click that, download it, and then once it’s downloaded double click to install and go through the install commands. So in the next video we’ll actually go ahead and create some files and get started.

Transcript 2

Hey, everybody, welcome back; in our last video, we got Typescript installed, node, with node npm installed, and we also installed the editor, we haven’t launched any of it yet, so let’s go ahead and create our first file, here, so we can actually open up our editor, say code dot, and if that didn’t open up for you, you can manually open up the editor, and you go up here, and you go File > Open, so here, we’ll see Open Editors, these will be files that we currently have open, which we don’t have any.

This is for searching, this is for source control, this is Debugging, and then here, we have Extensions, go ahead and type in typescript, and you’ll see one called TypeScript Hero; this is one I recommend, click the Install button, it will probably ask you to restart, you just click the button, and it will restart for you.

Perfect, so if we go back over here, we can click the New File button, or we can right click and say New File, and we’ll say main.ts for typescript, make this a little bigger, so you can see, and from here, we can start working on our project, so to get started, I’m going to type in export, and we normally don’t have to do this, this is just because we can get some weird errors, since we won’t actually be exporting or anything, we’ll just be doing all our commands in this one file.

So, the first thing we want to talk about is, normally, in javascript, when we declare a variable, we say var a equals 10, but we’re typically not going to use var if we can help it; what we want to use is let, and const, so let is just like var, except to the way it’s scoped, so let kind of helps you in some of those gotcha cases, it’ll actually scope it to the curly braces, so it’s block scoped, rather than var, is function scoped, so only when it’s in a function is it actually scoped.

So, that’s kind of one of the big problems with using var in JavaScript, is it all of a sudden gets hoisted and becomes globally scoped; const, on the other hand, you can’t re-declare it, so then, if I tried to say, c equals nine, it’s going to not like that, because, cannot assign c because it is constant, or a read only property, so that’s kind of one of the big perks, there.

Some of the other variables we have, we declare, are, we can say, number, so we don’t actually have to do an assignment, like in javascript, you actually do an assignment; here in typescript, we can actually just say this is equal to something, and it’s going to be of type, number, so later, when we got to declare, we say d equals hello, it’s not going to like that, because hello is not assignable to type number.

So it’s a really nice feature of typescript, kind of catching all those cases where we don’t want to reassign something to the wrong type, so change this back to a, here, we can also say string, and also, of the type of boolean, and then we also have the type, any, so this is very useful in cases where you have some api you’re calling, that you may or may not be getting back certain property; you may have some weird cases, you’re not sure what the type is going to be, could be a string, could be a number, could be boolean.

So, you want to use any, in that case, but if you use any, you’re not going to get some of the helpers that you normally get, or the intel sense, excuse me, static type checking that you normally get; there’s also a cool feature of strings, which I will show you now, let’s say b equals, and we use back ticks, and this is for string interpellation, and we can say ‘Hello World’ from a multiline!

We can save that, so this is perfect, and then, in here, what we can do, is we can actually transpile that code, so we can say tsc, or typescript, say target, we’ll say ECMAScript 2016, and let’s say dot slash, we’ll say main dot ts, that’s the file we want to transpile, and we could actually use the dash dash watch property, here, so that’ll just go ahead and run, and I’ll watch for any file changes, so we come back over here, we’ll see we have another file, called main js, and you’ll see it’s transpiling to ECMAScript 2016.

We could also do, so you want target 2015, and I’ll watch for changes, say this is a number, and we save, and you’ll see it’s saved here, let’s see, that doesn’t look right; we’ll just leave this off, here, I want to give it a target, there we go, because in ES2016, you can actually use let and const, so this is actually reverting back to ES5, where it’s actually using vars, which is really nice, so you can see here, it automatically is throwing in the new lines for us, so that’s some really, really, cool features that we wouldn’t normally get.

Transcript 3

So in our last video, we learned how to declare simple types, like boolean, number, NE.

Let’s go ahead and get rid of that for now. And let’s work on some more advanced types here. So we can say let string array. And you’ll make that a type. Let’s say string array. You can use capital S, lower case s. But this is declare an array of strings. So string array could equal hello world. Oop. And there again, we caught a type-o. Perfect. So you can see there, works great. We could also do call a generic array. And it’d be type array of string. So this is syntactically the same as this guy up here. Only difference, you can’t have a lowercase here. So this has to be uppercase, and the type is declared here. So then you could say generic array equals, and we could say, say hey and hello.

So these are pretty much both the same. So we come back here and run that. Oops. Then we can see our code is declared with vars. Everything’s looking good. So the next thing we’re gonna look at is a Tuple. So, a Tuple’s just like an array, essentially, in this case. But it happens to have different types. So these work great when the type is all string, or all number, or all boolean. But what if you had mix-match of types? Which would be what a Tuple could be good for. So, in this case, we could say let myTuple equal, oops, not equal, we’re declaring a type here, not setting it to a value. And we could say number boolean. Great.

And now we could say myTuple equals and if we say this, it’s gonna get an error. Hover over, ’cause it’s not assigned a type number and boolean. Okay, so let’s fix it. Say this is a three. It’s still gonna be an error, because this needs to be a boolean, which is a true or false. And we do that, and we see it resolves. Perfect. So one last type here I wanna show you is enum. And we’ll say colors. And we’ll declare some colors. We’ll say red, blue, green, whoops. And now we can say let color equal, uh, let color be of type colors. So we haven’t actually declared a variable, we’re just setting an enum.

So this type’s a little different from the Tuple since the Tuple’s basically an array. And then we can say let color, oop, say color equals colors dot red. Which would be, basically, a zero. So we say zero, it would be the same thing. So if you hover over, in the enum, if you don’t assign properties, the default is going to be setting it to its numerical place in the Tuple. But we could say red, blue, green to give them default properties. Now we see we have a problem, ’cause this is expecting a string called red. So that doesn’t even work anymore. So you’d have to go colors dot red. Now you see, now that fixes our problem.

So that works when they’re defaults, and they’re default to numbers. But once you start assigning them to values, that’s when you have some issues. So this may not be that helpful, but imagine if you had the word gray. And people misspell this all the time. They could put grey or gray. Just wanna make sure we use gray. So now if we went colors dot and we get type ahead, type gray, everything works great if we type gray with an e, that’s gonna be wrong. Perfect.

Then we go console dot log. And we can say color. And we come over here, we’ll compile it. And then we’ll say node. Main dot js. So we wanna run the js file. And we get the color gray. Perfect.

Interested in continuing? Check out the full TypeScript for Beginners course, which is part of our Full-Stack Web Development Mini-Degree.

]]>
Full-Stack Web Development Mini-Degree https://gamedevacademy.org/full-stack-web-development-mini-degree/ Sat, 17 Nov 2018 00:30:58 +0000 https://html5hive.org/?p=1961 Read more]]> Go from Zero to Full-Stack Engineer as you build web apps with HTML5, JavaScript, NodeJS, MongoDB, React, GraphQL, Angular, Git, AWS, and Azure. 

This project-oriented curriculum begins by covering the foundations of programming and web development. You’ll learn to create responsive and interactive websites as you get familiar with the basics. We’ll then move on to the server-side and introduce Node.js, Express, Mongo and other frameworks. You’ll be building webapps, REST API’s and scripts.

Following the server-side, we’ll delve further into front-end, this time covering modern frameworks for creating robust applications such as React and Angular. You’ll learn how to integrate these projects with Node.js back-ends and API’s. Finally, you’ll be shown how to use important tools such as Git and Github, and the deployment process to popular platforms such as AWS, Azure and Heroku.

Access this Mini-Degree on Zenva Academy

]]>
The Complete Programming and Full-Stack Bundle – 20 Course Smart Curriculum https://gamedevacademy.org/the-complete-programming-and-full-stack-bundle-20-course-smart-curriculum-html/ Fri, 02 Nov 2018 23:30:00 +0000 https://html5hive.org/?p=1967 Read more]]> ???????? Go from beginner to full-stack developer!

The Complete Programming and Full-Stack Bundle is the world’s most effective way to go from beginner to professional coder. Whether your goal is to advance your career, start your own business or expand your existing skill-set, our 20-course Smart Curriculum has something in store for you.

This bundle is suitable both for absolute beginners and more advanced developers. Projects cover a wide range of different topics including:

  • Crafting interactive websites and web applications with Bootstrap, Angular, React, Node and Express
  • Coding in Python and building smart Machine Learning and AI applications
  • Building games with Unity, Phaser and JavaScript
  • Creating stunning Virtual Reality games and applications
  • Game artwork creation with Blender and Gimp

Access The Complete Programming and Full-Stack Bundle on Zenva Academy

]]>
Complete Beginners Guide to Angular 4 https://gamedevacademy.org/getting-started-with-angular/ Wed, 20 Sep 2017 06:20:12 +0000 https://html5hive.org/?p=1765 Read more]]> Angular 4 is a complete and flexible application framework, mainly maintained by Google and a very active community. This version, commonly known just as Angular, was completely rewritten in TypeScript and is drastically different from its previous version, AngularJS; to the point of being considered in practice as two different frameworks. This new version has fixed many flaws found by the community over 5 years and has been improved in many factors like a better architecture, modern development tools, mobile by design, speed and performance.

Angular applications can be developed using TypeScript, Dart or JavaScript. For this tutorial we will be using TypeScript, initially having a brief introduction to it and a first contact with some of the basic elements that compose an Angular application.

You only need to have Node.js and Npm (Node.js Package Manager) installed, as well as the IDE / text editor of your choice; Visual Studio Code is highly recommended.

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

The versions for Node.js and Npm can be checked using the following command:

$ node -v
v6.11.2
$ npm -v
3.10.10

You need to have at least Node.js 6.9.x and Npm 3.x.x in order for this tutorial to work fine.

Introduction to Typescript

TypeScript is a programming language designed for large-scale application development. It’s a typed superset of JavaScript, meaning that it allow us to use features from the most recent ECMAScript versions and even some features that are not even in the scope of the standard yet. This is possible because when it’s compiled, its **transpiler** produces JavaScript in a cross-platform safe version.

The commmand-line TypeScript compiler can be installed using Npm:

$ npm install -g typescript

The version can be checked using the following command:

$ tsc -v
Version 2.5.2

Types

JavaScript counts with dynamic types, so when you declare a variable, you don’t define the type because it will be inferred during execution. This feature allows a variable to have different types, making the programming and debugging activities way more complex in the long run.

TypeScript adds optional static types, so when you declare a typed variable, its type will be enforced to be the same during the development process thanks to the type checking at compile time.

let foo: string = 'Hello TypeScript!';
foo = 0; // Error: Type "number" is not assignable to type "string"

The available basic types are: boolean, number, string, array, tuple, enum, any, void, undefined, null and never. It’s also possible to create custom types, check the handbook for further details.

Functions

Functions are the buildings blocks upon which JavaScript applications are built, so they play a key role in TypeScript as well. You can add types to named functions or anonymous functions:

// Named function
function add(x: number, y: number): number {
return x + y;
}

// Anonymous function
let myAdd = function(x: number, y: number): number {
return x+y;
};

More on functions can be found in the handbook.

Classes

Object-oriented programming (OOP) has been a very popular programming paradigm during the last decades mostly because of its level of scalability and modularity. Traditional JavaScript supports this paradigm but it uses prototypes for inheritance instead of classes, however latest versions of the standard introduced the possibility to use a class-oriented approach.

This new approach can be considered as syntactical sugar because it doesn’t change the existing prototype-based inheritance model, but allows a simpler way to create objects and manage inheritance. TypeScript allows us to use these techniques now without having to wait for the browsers to support them.

In general, a class is composed of a name, attributes and methods. The syntax to create a simple class looks like this:

class Person {
  private name: string;

  constructor(name : string) {
    this.name = name;
  }

  greet() {
    console.log("Hi! I'm " + this.name);
  }
}

This class is named Person and contains one attribute (name) and two methods (constructor and greet).

When an object is created by the constructor of a specific class, this object is called an instance of the class.

let person: Person = new Person("John Doe");

Now that you have created person, you can use the behaviour implemented in the class. In this case, the greet method:

person.greet();

The console output is: Hi! I’m John Doe.

Finally, one of the main features in OOP paradigm is the possibility to create new classes based on others using inheritance. For instance, it’s possible to extend a basic Calculator class into a more advanced ScientificCalculator class that inherits all the properties and methods existing in the parent class by using the keyword extends:

class Calculator {
  model: string;
  constructor(model : string) {
    this.model = model;
  }
  add(x: number, y: number): number {
    return x + y;
  }
  subtract(x: number, y: number): number {
    return x - y;
  }
  multiply(x: number, y: number): number {
    return x * y;
  }
  divide(x: number, y: number): number {
    return x / y;
  }
}

class ScientificCalculator extends Calculator {
  constructor(model : string) {
    super(model);
  }
  pow(base: number, exp: number): number {
    return base**exp;
  }
  sin(rad: number): number {
    return Math.sin(rad);
  }
  cos(rad: number): number {
    return Math.cos(rad);
  }
}

 

Interfaces

One of the most important principles in TypeScript is type-checking, and this focuses on the shape. In many scenarios you might need to implement a custom type instead of just using the primitive ones.

An interface in object-oriented languages is a an abstract type that defines behaviours as method signatures. It can be considered as a code contract, in order to implement it you need to follow its rules.

For instance, you can create an interface called LabelledValue, this would be a custom type that assigns a label to a value:

interface LabelledValue {
label: string;
value: number;
}

let lv: LabelledValue = { label: "Label X", value: 1001 };

In case of not following the contract, in this case by not providing the required elements:

let lve: : LabelledValue = { label: "Label Y" };

The transpiler would alert of this error with a message like: Type “{ label: string }” is not assignable to type “LabelledValue”. Property “value” is missing in type “{ label: string }”.

Decorators

Decorators are a new way to add annotations and a meta-programming syntax for class declarations, methods, accessors, properties or parameters. They are an experimental feature proposed for future versions of JavaScript that can be enabled in TypeScript.

Decorators have a special syntax using a prefixed @ symbol and followed by an expression that must evaluate to a function that will be called at runtime. This means that at the basic level, they are functions that can augment a class, a parameter, a method or a property.

For now, you only need to identify them and to know that they are widely used to manage Angular architecture under the hood. For example, one very common decorator is the `Component` decorator, applied in this case to the MyComponent class declaration:

@Component()
class MyComponent {
}

Modules

Modules can be seen as containers, these help to separate the code in a way that helps to optimize organization, re-usability, and encapsulation. These allow to separate code and data into files that isolate features, in other languages they are called libraries, packages, etc.

Modules are executed within their own scope, this means that variables, functions, classes, interfaces, etc. declared in a module are not visible outside the module unless they are explicitly exported. Any declaration (such as a variable, function, class, type alias, or interface) can be exported by adding the export keyword.

Creating a basic Angular application

With the previously acquired understanding of TypeScript, it’s possible to get hands on creating a very basic Angular application.

Setup

In order to simplify the setup process and save some time, we are gonna use Angular CLI. This is a command line interface tool with an extense set of features, but for now we will use it just to setup our Angular project.

You can use the following command in order to install Angular CLI globally:

npm install -g @angular/cli

Now we are gonna generate a new project with the application skeleton:

ng new my-app

After everything as been setup and all the dependencies have been installed, you will see something like this:

installing ng
  create .editorconfig
  create README.md
  create src/app/app.component.css
  create src/app/app.component.html
  create src/app/app.component.spec.ts
  create src/app/app.component.ts
  create src/app/app.module.ts
  create src/assets/.gitkeep
  create src/environments/environment.prod.ts
  create src/environments/environment.ts
  create src/favicon.ico
  create src/index.html
  create src/main.ts
  create src/polyfills.ts
  create src/styles.css
  create src/test.ts
  create src/tsconfig.app.json
  create src/tsconfig.spec.json
  create src/typings.d.ts
  create .angular-cli.json
  create e2e/app.e2e-spec.ts
  create e2e/app.po.ts
  create e2e/tsconfig.e2e.json
  create .gitignore
  create karma.conf.js
  create package.json
  create protractor.conf.js
  create tsconfig.json
  create tslint.json
Installing packages for tooling via npm.
Installed packages for tooling via npm.
Successfully initialized git.
Project 'my-app' successfully created.

Angular CLI configures a lot of elements commonly used when developing Angular applications. Now we can go inside my-app directory:

cd my-app

It’s possible to start the application with the following command:

$ ng serve --open

This will open your browser in http://localhost:4200/ and if everything is working fine you should see a basic page with the Welcome to app! title.

 

Besides launching the application, Angular CLI also watches the files, and rebuilds the app as we make changes to those files.

Angular CLI created a lot of files that may be overwhelming for a first contact, but for the moment we are only interested in the src directory, and particularly in the app directory inside src.

src
|-app
|-app.component.css
|-app.component.html
|-app.component.spec.ts
|-app.component.ts
|-app.module.ts

Components

Components could be considered as the most important concept behind Angular applications, these might be seen as the building blocks of our project and are defined in the official documentation as: “A component controls a patch of screen called a view.

We separate our application in different components, each one of them will be composed by the component’s logic and the view that will be visible to the user.

An Angular application can be modeled as a tree of these components, each one of them having its own selector.

For instance, in our boilerplate application we already have one component called app-root that will be, as expected, the root component of our application.

Component structure

let’s start by checking the file called app.component.ts, this contains a class called AppComponent and some other elements:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
}

In order to have an Angular component, we need to import Component from Angular. After this, we can use a class decorator in order to extend the AppComponent class with component behaviour. Decorators in general have a @ prefix and in this case we see the @Component decorator before our class

The view is placed inside the class decorator and the component logic inside the class.

Component selector

Our application can be modeled as a tree of components, where each one of them has its own selector.

A selector is the way to use our component, because it will tell Angular to create an instance of the particular component. In this case, AppComponent uses the app-root selector. This is accomplished in the class decorator with the selector property:

selector: 'app-root'

At the moment we only have one component, app-root, but after some work we could end up with a tree like this:

<app-root>
<my-search></my-search>
<my-list>
<my-list-item></my-list-item>
<my-list-item></my-list-item>
<my-list-item></my-list-item>
</my-list>
</app-root>

Component template

The component’s template refers to the content that will be loaded where the selector has been placed. This is very similar to traditional HTML and almost all HTML syntax is valid template syntax, but we have the ability to extend the HTML vocabulary of our templates with other components, directives, pipes, etc.

A very basic template for our component could be set with the template property inside our class decorator.

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: '<h1>My First Angular App</h1>'
})
export class AppComponent {
}

Angular CLI has gone one step further, and created our component template in a file called app.component.html. That is then linked in the class decorator with the templateUrl property.

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
}

Let’s clean the app.component.html file and just leave the following template:

<h1>My First Angular App</h1>
Angular Basic Component Template

We can also add some basic style in our app.component.css:

h1 {
  color: blue;
}
Angular Basic Component Style

Now we have understood how a basic component works, but this component isn’t dynamic at all, its template is completely static and there is no logic defined yet.

Interpolation

We would like to leave behind static data and move into dynamic data, and with Angular we can display data by binding controls in our template to properties of our component that can be changed according our component’s logic.

We will start by learning how to use interpolation, the first form of data binding, in order to add dynamic behavior to our component.

We already have a class property called title with the string app, let’s change it to My First Angular App. Let’s also add a property called subtitle in our class with the string using interpolation!:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'My First Angular App';
  subtitle = 'using interpolation!';
}

We use double-curly braces, {{  }}, in order to use interpolation in our template. Inside the braces we have the name of our component property, being app or subtitle. By doing this, Angular is able to replace {{ property }} with the corresponding string value.

<h1>{{ title }}</h1>
<h2>{{ subtitle }}</h2>

Now our component renders like this:

Component Using Interpolation

Directives

Angular templates have been very simple so far, just using basic h1 and h2 tags, but we can use directives to transform the way they are rendered by adding dynamic behaviour.

We can categorize directives in two types: structural and attribute directives.

A component could be considered as a directive with a template, but taking into account their central and distinctive role, they are separated from structural and attribute directives.

We will see that a component is the most common of the three directives and we write lots of them as we build our application.

Structural directives

Structural directives alter our layout by adding, removing, and replacing elements in DOM. They tend to appear within an element tag as attributes do, sometimes by name but more often as the target of an assignment or a binding.

Attribute directives

Attribute directives change the appearance or behavior of an element, but they don’t affect the template.

As an initial tutorial, we will one of the most common structural directives, known as NgIf.

NgIf

NgIf is a structural directive that renders components or elements based on the evaluation of a condition. It takes the condition result, true or false, and makes an entire chunk of DOM appear or disappear.

Let’s suppose we add another property to our AppComponent called showMessage, it would look like this:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'My First Angular App';
  subtitle = 'using interpolation and directives!';
  showSubtitle = false;
}

We could then use this property and NgIf directive to decide when to show our subtitle with the syntax *ngIf=”condition” in the h2 element.

<h1>{{ title }}</h1>
<h2 *ngIf="showSubtitle">{{ subtitle }}</h2>

In this case our app would look like follows:

NgIf Directive With A False Value

 

 

But if we change showSubtitle = false; to showSubtitle = true;, it would render our element:

NgIf Directive With A True Value

 

Pipes

Most of applications deal in some point with a common task: get data, transform them, and show them to users. Angular provides a way to transform data called pipes, providing the most frequent transformations out of the box, as well as giving us the option to create our own custom pipes.

A pipe takes in data as input and transforms it to a desired output. They can be used directly in our template, what makes them very useful and convenient when developing an application.

The common template syntax to use a pipe with some input data is: {{ data | pipe }}.

Built-in pipes

Angular comes with a stock of pipes such as date, uppercase, lowercase, currency, etc. These are all immediately available for use in any template.

Let’s use a pipe to transform the title property in this AppComponent component:

<h1>{{ title | uppercase }}</h1>
<h2 *ngIf="showSubtitle">{{ subtitle }}</h2>

Our app would look like this:

Uppercase Pipe

All Right! I’m In, now what?

This has been a very introductory tutorial to Angular and some of its modern features, but there is a lot more to explore. So if you have enjoyed this tutorial and want to deepen your understanding of this fantastic framework, please take a look to the Services Tutorial. Also feel free to leave a comment below with any feedback or questions that you might have.

]]>
Source Code – AngularJS Course https://gamedevacademy.org/source-code-angularjs-course/ Wed, 26 Oct 2016 07:47:39 +0000 https://html5hive.org/?p=1989 Download the source code here.

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

]]>
The Complete MEAN Stack Development Course https://gamedevacademy.org/the-complete-mean-stack-development-course/ Mon, 24 Oct 2016 00:03:27 +0000 https://html5hive.org/?p=1635 Read more]]> Learn the different aspects of full stack JavaScript development using the MEAN stack. We’re not talking about any generators or MEAN frameworks here, we’re talking about a full understanding of MongoDB, Express, AngularJS, and Node.js.

Learn how to build full stack applications in JavaScript using the MEAN technologies. Architect MEAN stack applications from scratch. Design and build RESTful APIs using Node.js, Express, and MongoDB. Create and use MongoDB databases. Develop modular, maintainable Single Page Applications using AngularJS and more.

Access this course on Zenva Academy

]]>
Learn Angular 2 and TypeScript from Scratch https://gamedevacademy.org/learn-angular-2-and-typescript-from-scratch/ Mon, 24 Oct 2016 00:01:48 +0000 https://html5hive.org/?p=1616 Read more]]> If you want the competitive edge with anything dealing with mobile and desktop web apps, you simply must know Angular 2. Angular is a development platform for building mobile and desktop web applications. It is a structural framework that allows you to use HTML as your template language and it is JavaScript based. It’s mostly maintained by Google and Angular 2 is the latest version of the framework.

With 5 hours of content, this Angular 2 online course will give you a thorough understanding of how Angular 2 solutions are designed, administered, and developed. If you’re a web, mobile or service app developer, architect, UI designer, tester or administrator, or if you just want to know how to get Angular 2 projects up and running, then this is the course for you. And if you’re just getting started with Angular, this is the perfect introduction course.

Access this course on Zenva Academy

]]>
Getting Started with Angular 2 https://gamedevacademy.org/getting-started-with-angular-2/ Thu, 01 Oct 2015 03:59:45 +0000 http://html5hive.org/?p=965 Read more]]> Angular 2 is still in Alpha, however it can be used today, and it’s a good idea to get a jump start on the future to give you that competitive edge. If you are experienced at all with Angular 1.x then some of the concepts such as Directives, Controllers, and Services will be a little familiar to you. However, Angular 2 is completely different than the first. Many of the concepts such as modules and providers have been for the most part replaced with (future) native JavaScript implementations. This is one reason that the Angular team chose to rewrite everything from the ground up, keeping focused on the future of JavaScript (EcmaScript) in mind from the very start.

Normally when developing web applications, I would say that you can use whatever IDE / text editor that you want. While that is technically still true, in this case I’m going to specifically recommend that you use Visual Studio Code. A free cross platform editor developed by Microsoft, I believe that this is going to be the best tool primarily because of Intellisense.

You’ll also need to have node.js  and npm installed and be comfortable with the basics. If you aren’t up to speed with node, you can check out my beginner’s article on the subject or this video course at Zenva Academy.

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

Tutorial Source Code

All of the source code for this tutorial can be downloaded here: source code .

Quick Primer on TypeScript and ES6

TypeScript, much like ES6, is a superset of JavaScript and adds features while leaving the original language there. It has a compiler / transpiler that produces JavaScript, it was created by Microsoft and is also open source. It is the core language being used to write Angular 2, and the recommended path for writing applications in Angular 2. The compiler comes pre-installed with Visual Studio, or you can grab it as a node package.

npm install -g typescript

Statically Typed Variables

In TypeScript, variables can (and should be) strongly typed. It doesn’t have any bearing on code execution, because it’s still just JavaScript, but what it does give you is a way for the compiler to let you know about mistakes and hopefully avoid side effects. The available basic types are: boolean, number, string, array, enum, any, and void. You can also create custom types. Check the handbook for further details.

function foo(bar: string, baz: number) {
    return bar + baz;
}

// ...

foo('boo', 'beep'); // compiler error!

Classes

Classes in TypeScript follow the ES6 standard for classes. JavaScript doesn’t have true classes like traditional OOP languages, rather they are simply sugar to help make inheritance easier. Classes provide a clean way to declare a constructor, methods and variable members. TypeScript further enhances them by providing the notion of scoping and static typing. Within the end result JavaScript there is still no such thing as a private variable, however the compiler can check and throw errors to warn you about improper usage. Classes can also be subclassed using the extends keyword, and automatically give you the super method for utilizing the implementation of the parent.

class Animal {
    public name: string;
    public sound: string;

    private feet: number;

    constructor(name: string, sound: string, feet: number) {
        this.name = name;
        this.sound = sound;
        this.feet = feet;
    }

    speak() {
        console.log('The ' + this.name + ' says ' + this.sound);
    }
}

class Dog extends Animal {
    constructor() {
        super('dog', 'bark', 4);
    }
}

var fido: Dog = new Dog();
fido.speak();

In order to accomplish this in ES5 the code is a lot less clean and readable, though it still can be done using the standard way to inherit from a prototype in JavaScript.

function Animal(name, sound, feet) {
    this.name = name;
    this.sound = sound;
    this.feet = feet;
}

Animal.prototype.speak = function() {
    console.log('The ' + this.name + ' says ' + this.sound);
};

function Dog() {
    Animal.call(this, 'Dog', 'bark', 4);
}

Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

var fido = new Dog();
fido.speak();

Interfaces

An interface defines a contract of methods and variables that must be implemented by a class or be the signature for a variable type. A class can be designated to have an interface using the implements keyword. Interfaces can extend each other similar to classes. If the contract is not fulfilled the compiler will provide errors to warn you.

interface IVector2D {
    x: number;
    y: number;
}

interface IVector3D extends IVector2D {
    z: number;
}

interface WorldObject {
    position: IVector3D;
    rotation: IVector3D;
    scale: IVector3D;
}

class Vector implements IVector3D {
    constructor(public x: number, public y: number, public z: number) { }

    add(otherVector: Vector) {
        this.x += otherVector.x;
        this.y += otherVector.y;
        this.z += otherVector.z;
    }

    toJSON() {
        var x = this.x,
            y = this.y,
            z = this.z;

        return { x, y, z };
    }
}

class GameObject implements WorldObject {
    position: Vector;
    rotation: Vector;
    scale: Vector;

    name: string;

    constructor(name: string) {
        this.name = name;
        this.position = new Vector(0, 0, 0);
        this.rotation = new Vector(0, 0, 0);
        this.scale = new Vector(1, 1, 1);
    }

    translate(amount: Vector) {
        this.position.add(amount);
    }
}

var foo = new GameObject('Fooman Choo');
console.log(foo.position);
// {x: 0, y: 0, z: 0}
foo.translate(new Vector(2, 3, 0));
console.log(foo.position);
// {x: 2, y: 3, z: 0}

Decorators

Decorators are actually a feature slated for ES7, and so they are still listed as experimental within TypeScript. They are however, super cool, and Angular 2 is making use of them so they are important to understand. There are four types of decorators: Class, Method, Property, and Parameter. Most often you will encounter Class decorators while working with Angular.

A class decorator is a function that takes the class (constructor) as an argument, and it allows us to modify that constructor before each instance is created. If the decorator function returns a function, that function will be the new constructor.

In the following example “Secured” is the function that will be used as a decorator. Decorators are applied using the @ sign and placed on top of the object they are decorating. This demonstrates the power of decorators being that at design time we can configure classes to have a specific behavior. We could have instead set the allowedRoles property on the instance after it was created, but that would need to happen at runtime. We could have also instead created a subclass or separate class for each with hard coded defaults. Using decorators this way is a much more componentized approach.

enum UserRoles {
    'None'          = 0,
    'Registered'    = 1 << 0,
    'Admin'         = 1 << 1,
    'Moderator'     = 1 << 2
}

function Secured(roles: UserRoles[]) {
    return function(target: any) {
        target.prototype.allowedRoles = roles;
    }
}

class User {
    roles: UserRoles = UserRoles.None;

    constructor(public name: string, roles: UserRoles[]) {
        let r = UserRoles.None;
        roles.forEach(function(role) {
            r |= role;
        });
        this.roles = r;
    }
}

class BaseService {
    name: string = 'BaseService';
    allowedRoles: UserRoles[];

    constructor() {}

    protected isAuthorized(user: User): boolean {
        let allowed = this.allowedRoles.every(function(role) {
            return ((user.roles & role) === role);
        });

        return allowed;
    }

    securedMethod(user: User): any {
        return 'foo';
    }
}

@Secured([UserRoles.Moderator, UserRoles.Admin])
class ServiceA extends BaseService {
    name: string = 'ServiceA';

    securedMethod(user: User): any {
        let allowed = this.isAuthorized(user);

        if (!allowed) {
            throw new Error(user.name + ' failed the security check!');
        }

        return 'highly classified data';
    }
}

@Secured([UserRoles.Registered])
class ServiceB extends BaseService {
    name: string = 'ServiceA';

    securedMethod(user: User): any {
        let allowed = this.isAuthorized(user);

        if (!allowed) {
            throw new Error(user.name + ' failed the security check!');
        }

        return 'normal user data';
    }
}

var normalUser = new User('Bob', [UserRoles.Registered]);
var adminUser = new User('Steve', [UserRoles.Registered, UserRoles.Moderator, UserRoles.Admin]);
var serviceA = new ServiceA();
var serviceB = new ServiceB();

function access(user: User, service: BaseService): void {
    try {
        console.log(user.name + ' accessed ' + service.name + ' and found ' + service.securedMethod(user));
    } catch (e) {
        console.error(e.message);
    }
}

access(adminUser, serviceA);
access(normalUser, serviceA);

access(adminUser, serviceB);
access(normalUser, serviceB);

/*
Steve accessed ServiceA and found highly classified data
Bob failed the security check!
Steve accessed ServiceA and found normal user data
Bob accessed ServiceA and found normal user data
*/

The actual decorator function is the inner function in the Secured method. In order to provide configuration to the decorator (which takes a specific signature) we can wrap it as we did in a factory function returning the decorator method and gaining access to the outer method’s scope.

One other thing that you may not be familiar with in the above example is the use of enum . Enumerations are a concept found in many other languages and are basically a special type of Object. Check the TypeScript handbook on this subject for more details.

The second type of decorators modify properties of an object. Property decorators take the prototype of the object being decorated, and the key of the property. An example of a property decorator is the @validate  decorator below. We can setup a custom getter and setter to perform validation based on validation method passed in.

function validate(validator: Function) {
    return function(target: any, prop: string) {
        var val = this[prop];

        Object.defineProperty(target, prop, {
            enumerable: true,
            configurable: true,
            get: function() {
                return val;
            },
            set: function(value) {
                if (validator(value)) {
                    val = value;
                    console.info('Validation success!', value);
                } else {
                    console.error('Validation failed! ', value);
                }
            }
        })
    };
}

class Foo {
    @validate((value) => value > 0)
    count: number;
}

var foo = new Foo();
foo.count = 3; // OK
foo.count = -1; // ERROR!

While TypeScript will validate that the type of the variable count is in fact a number, it won’t be able to validate the business rules.  As you can see, this function is simply modifying the prototype of Foo and adding custom getter and setter based on the passed in callback method. This is also something that can be achieved in plain JavaScript, however adding a simple validate statement above the property is much cleaner and very readable.

The syntax for the callback method that I’ve used is ES6 “fat arrow” function syntax. You can read more about this in the documentation, however basically it creates a function with arguments on the left, and the return value on the right of the “fat arrow”.

Methods can have decorators as well, you pass in the function being decorated, the name of the function, and its descriptor.

function log(target: Function, key: string, descriptor: any) : MethodDecorator {
  var originalMethod = descriptor.value; 

  descriptor.value =  function (...args: any[]) {
      var a = args.map(a => JSON.stringify(a)).join();
      var result = originalMethod.apply(this, args);
      var r = JSON.stringify(result);
      console.log(`Call: ${key}(${a}) => ${r}`);
      return result;
  }

  return descriptor;
}

class Foo {
	@log
	add(a: number, b: number): number {
		return a + b;
	}
}

var foo = new Foo();
foo.add(1, 2);

While you can create your own decorators, you probably aren’t going to need to at least at first, but now you will have a better understanding of what is going on in the Angular 2 code.

Modules

There are several different choices for doing modules in ES5: require.js, amd, system, etc. Even Angular 1 had its own module system in place to enable you to namespace things easily across multiple files and not pollute the global namespace.

In TypeScript modules can be both internal and external. Internal modules are created using the module keyword. They are “internal” to TypeScript as in they compile to function closures rather than using some other module system such as AMD or CommonJS.

module foo {
    export var bar: number = 32;
}

module baz {
    var bing: number = 88;
    export var bar: number = 77;

    export function log(): void {
        console.log('inside: ', bing, bar);
    }
}

console.log('foo: ', foo.bar, ' baz: ', baz.bar);

Variables are exposed using the export  keyword, anything that is not exported is scoped to the module and inaccessible from the outside. Modules can span multiple files, adding a reference tag will let TypeScript know where to load the details about the existing module from.

/// <reference path="modules.ts"/>

module baz {
    export class Bar {
        constructor(public foo: string) {

        }
    }
}

var bar:baz.Bar = new baz.Bar('fun!');
console.log('bar', baz.bar, 'class: ', bar);

External modules are the ones that compile to either AMD (require.js) or CommonJS (node.js). Within TypeScript you will use the ES6 module loading syntax. These are the types of modules that Angular 2 will use and so you will see this throughout the examples. Instead of using the module keyword, the file itself is considered the module. Variables and objects that are not exported are scoped to the file.

(modules_external.ts)

var foo:string = 'bar';

export function getFoo(): string {
    return foo;
}

export var BAR:string = 'BAR';

export class Baz {
    constructor(public name: string) {}
}

This can then be referenced in another file like so (modules_external2.ts):

import {getFoo, Baz} from './modules_external';

console.log('foo: ', getFoo(), 'baz: ', new Baz('Herman'));

You can selectively import objects from the module, or use * to grab everything. If you are familiar with node.js or require.js then this will likely be familiar to you.

There is a lot more to TypeScript and ES6, and I encourage you to study the documentation and resources available for them, but we want to start working on Angular 2 applications now. This primer should enable you understand enough to proceed with that.

Creating a basic Angular2 App

Now that you have an understanding of TypeScript and the upcoming features of JavaScript, we can finally get to actually creating an Angular 2 application. First, we’ll need to download a few libraries. We need of course the main Angular 2 library, also systemjs so that we can load our module, and traceur which handles some of the polyfills for the ES6 features that Angular is using. I’ve actually had the most luck using a tool called jspm. Similar to npm jspm is designed to grab needed dependencies from both npm as well as github (and other repositories). It takes all of those dependencies and prepares them to be loaded using systemjs. It will generate a config.js file that will setup systemjs so that it’s easy to launch your apps. It will also build a bundle file for when you are ready to release.

npm install -g jspm

We’ll create a folder for our project and use jspm instead of npm to install our dependencies, it will augment the package.json that npm would normally use, you can use them side by side. If you are going to use the included source code files, then you can simply run npm install && jspm install  and it should load everything you need.

jspm install angular2 traceur-runtime es6-shim reflect-metadata zone.js typescript

It will install all of these libraries and also install systemjs (we don’t have to tell it to). It will also create a config.js file that is populated with some of the information needed to pass to systemjs. Now we can create an index.html file that looks like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Getting Started with Angular 2</title>
</head>
<body>
    <app></app>

    <script src="jspm_packages/system.js"></script>
    <script src="config.js"></script>
    <script>
        System.import('app/hello');
    </script>
</body>
</html>

There are a couple of things to note about what we have here, first we have the <app>  element. Similar to Angular 1, we can create custom elements and bind them to the Angular context, we’ll define that in our code. We need to load system.js that jspm has installed for us, as well as the config file that it has generated. Finally, we’ll start everything up by importing the hello module from app, we’ll create that file in a moment. While jspm has generated a basic config file for us, we need to make a few additions to it in order to get everything running the way that we want. We need to add in options to pass to the TypeScript compiler, so that it knows that we are targeting ES5 browsers, using the systemjs module type, and also using the experimental decorators feature.

typescriptOptions: {
    "compilerOptions": {
      "target": "ES5",
      "module": "system",
      "sourceMap": true,
      "emitDecoratorMetadata": true,
      "experimentalDecorators": true,
      "removeComments": false,
      "noImplicitAny": false
    }
  }

We also want to have it automatically transpile our ts files into js files on the fly, to make development easier. In order to accomplish that, we need to define a package, which is essentially a folder, and tell it to look for ts instead of js files.

packages: {
    "app": {
      "defaultExtension": "ts"
    }
  }

You’ll also want to install the TypeScript definition file manager tsd so that the compiler and IDE can understand the Angular 2 library. TypeScript “typings” are like forward declarations of types and interfaces, as well as documentation. It lets TypeScript know the shape of 3rd party libraries that you might be using so that it can do its type checking against them.

npm install -g tsd

Once that is installed, we’ll use it to download the core set of definition files for Angular. It will create a “typings” folder that contains all of the various definition files. At the top of the folder, it will create a “tsd.d.ts” file which is a roll up of all the dependencies so that you can load just one file at the top of your app.

tsd install angular2 es6-promise rx rx-lite --save

Now we’ll create a folder called “app”, and inside a file called “hello.ts”. At the top we’ll need to include a reference to roll up typings file. We need to import the 3rd party libs and then we’ll import Component, View and bootstrap from the angular2 module.

/// <reference path="../typings/tsd.d.ts" />

import 'zone.js';
import 'reflect-metadata';
import 'es6-shim';
import {Component, View, bootstrap} from 'angular2/angular2';

A Component is similar to a directive in Angular 1. Any directive that requires a view, much like the items used in ng-view or a custom directive with a specialized view. Angular provides a @Component  class decorator that is configurable. We pass in a selector that essentially translates directly to what you would pass into document.querySelector  call. Since the selector we are passing in is just “app”, we are creating a element component using the tag <app> .

A component also requires a @View  decorator that among other things allows us to describe the template that will be used by the component. We can use ES6 template strings to create nice multi-line templates, but we still use Angular’s double handlebars syntax to bind to “scope” variables.

Finally, the class that you are decorating is your controller. Similar to using the “controllerAs” syntax in Angular 1, the public variables and methods are available within the scope of the template.

@Component({
    selector: 'app'
})
@View({
    template: `
        <div>Hello {{ name }}</div>
    `
})
class App {
    name: string = 'World';
}

The last item that we imported is bootstrap, which much like in the first version is a method to initialize all of the components and modules within the framework. For now, we simply have one component, so we pass the App class to it to get things started. Instead of bootstrapping to a DOM element like we did in Angular 1, this time we are setting the root of our tree to a specific class (function). Much like the original bootstrap method, you can pass in an array of items for the dependency injector as well, we’ll do that later on.

bootstrap(App);

 

Because files are going to be dynamically loaded via ajax, you can’t simply open the index.html file in the browser. Instead you’ll need to host it as a local web server. You can use any web server that you want, if you don’t know of one to use, you can install live-server .

npm install -g live-server

Once that is installed, simply execute it from the location that you want to serve. It will open the browser for you and watch for changes to automatically refresh as you develop.

Components

Right now we have just a single Angular “application” root. We want to break things down into components to build up our application views. Let’s take our little “Hello World” message out of the main application, and create a separate component for it.

@Component({
    selector: 'hello',
    properties: ['name']
})
@View({
    template: '<div>Hello {{ name }}</div>'
})
class HelloComponent {
    name: string = 'World';
}

As you can see, this looks very much like the App component that we used to have, and this is because they are both components. Everything in Angular 2 is just a tree of components. The other services and directives exist only to assist the components in doing their job, which is rendering a view.

One thing that is new here however, is the properties attribute added to the component definition. This allows us to bind values from attributes defined on the element to the properties of our component class.

Now we need to update our main App component to reference and display our HelloComponent.

@Component({
    selector: 'app'
})
@View({
    template: `
        <div>
            <hello [name]="myName"></hello>
        </div>
    `,
    directives: [HelloComponent]
})
class App {
    myName: string = 'Ben';
}

Now instead of directly outputting the name into our template, we include the markup for our <hello> tag. This time around, attributes take a special syntax as well, for a non method (event) we use the square brackets. This helps differentiate the attributes from standard HTML attributes and decreases the work that everyone has to do to recognize them. Method attributes are surrounded in parentheses, we’ll take a closer look at them in a bit. Finally, we also need to declare the directives that are expected to be found in the template. This is because there is no Angular module system to list out the dependencies anymore, also it is easier on the compiler to not have to check every single element in the DOM.

Directives

Directives are similar to directives in Angular 1, however they do not have a view. In Angular 1 essentially Directives and Components were the same thing, now they are separate animals.

We can declare a directive using the @Directive  decorator to decorate a class. Our selector should use the square brackets attribute notation. We want to pass in the color to hover via the same attribute as the directive, but since we have a hyphen in there, we need to rename it so that it can map to a property in the class. The host property allows us to configure some things on the “host” element. We want to hook into the mouseenter  and mouseleave  events, the syntax for events uses parentheses. On the right side we are mapping these events to method handlers in the class. The $event is available just like in Angular 1, however for this simple directive we don’t need it.

In order to access the element that the directive is attached to, we need a special type called ElementRef . We also need to be able to use dependency injection to get an instance of it passed to our class constructor. The @Inject  decorator tells Angular to do just that. Once we have that, we can use it in our event handlers to change the background color of the element on “hover”.

@Directive({
    selector: '[hover-color]',
    properties: ['color:hover-color'],
    host: {
        '(mouseenter)': 'on($event)',
        '(mouseleave)': 'off($event)'
    }
})
class HoverColorDirective {
    color: string;
    el: ElementRef;
    private _oldColor: string;

    constructor(@Inject(ElementRef) el: ElementRef) {
        this.el = el;
        this._oldColor = this.el.nativeElement.style.backgroundColor || '#fff';
    }

    on(event) {
        this.el.nativeElement.style.backgroundColor = this.color;
    }

    off(event) {
        this.el.nativeElement.style.backgroundColor = this._oldColor;
    }
}

We also need to add the new types ( Directive ElementRef, Inject ) to our import statement. Then we can update our HelloComponent (or any component) to use our new directive.

import {Component, View, bootstrap, Directive, ElementRef, Inject} from 'angular2/angular2';
@Component({
    selector: 'hello',
    properties: ['name']
})
@View({
    template: '<div [hover-color]="color">Hello {{ name }}</div>',
    directives: [HoverColorDirective]
})
class HelloComponent {
    name: string = 'World';
    color: string = 'pink';
}

There are also built in directives, one of the more frequently used directives from Angular 1, ng-repeat, has returned, but is now called ng-for. We need to import the type again before we can add it to the component’s list of directive dependencies. We can either specifically import NgFor  as I have done, or we can import a special array of directives called CORE_DIRECTIVES .

@Component({
    selector: 'app'
})
@View({
    template: `
        <h1><hello></hello></h1>
        <div>
            <hello *ng-for="#myName of names" [name]="myName"></hello>
        </div>
    `,
    directives: [HelloComponent, NgFor]
})
class App {
    names: string[] = ['Ben', 'Pablo', 'Lukas', 'World', 'Angular'];
}

The syntax for ng-for is a little different, you start it with an asterisk (*). This is special sugar to expand the directive into a template component. The hash sign on the syntax inside provides that variable name to the child scope inside. Since the documentation is not quite ready yet, this blog post explains this in greater detail.

Services

Obviously rendering static variables isn’t very exciting, we want to work with more complex data and services. Creating a service in Angular 2 means simply creating a class just like any other.

class DataService {
    getFriends(): string[] {
        return ['Ben', 'Pablo', 'Lukas', 'World', 'Angular'];
    }
}

The DataService is a simple one with only one method, but now we can update our get the data about our friends from a service instead of baking it directly into the component.

While we’re at it, let’s further componetize our app, we can pull the friends listing out of the main App component and add it into a “friends-list”. When a component needs to access services, similar to how the view needs a list of directives, it needs a list of bindings. We pass in our DataService to the bindings, and then @Inject  it into our constructor.

@Component({
    selector: 'friends-list',
    bindings: [DataService]
})
@View({
    template: `
        <div>
            <h2>Friends</h2>
            <hello *ng-for="#friend of friends" [name]="friend"></hello>
        </div>
    `,
    directives: [HelloComponent, NgFor]
})
class FriendsList {
    friends: string[];

    constructor( @Inject(DataService) service: DataService) {
        this.friends = service.getFriends();
    }
}

Finally, we can update our App component to use the new friends-list.

@Component({ selector: 'app' })
@View({
    template: `
        <friends-list></friends-list>
    `,
    directives: [FriendComponent, FriendsList]
})
class App {

}

Of course, even this service is really static, normally we are going to want to load data from an external source over HTTP. Angular has again provided a wonderful Http service that we can use.

Because the http module isn’t part of the angular2 module, but a separately loaded file, we need to add it to the paths in our config.js file so that jspm knows where to find it.

paths: {
    "npm:*": "jspm_packages/npm/*",
    "github:*": "jspm_packages/github/*",
    "angular2/http": "jspm_packages/npm/angular2@2.0.0-alpha.37/bundles/http.dev.js"
  },

We also need to install the typings file so that the IDE / compiler understands the the library.

tsd install angular2/http

A new import line at the top will pull in the types that we need. Specifically we need the Http  service, and we also need HTTP_BINDINGS  which is an array of other dependencies that we will pass into the bootstrap method.

import {HTTP_BINDINGS, Http} from 'angular2/http';

Now we need to add the Http  service to the DataService  class. Just like before we @Inject  it into the contstructor, we’ll assign it to a member variable so that we can access it in later methods. Angular 2 favors Rx event streams, so we convert the request to a Rx stream and grab the json data.

class DataService {
    http: Http;

    constructor( @Inject(Http) http: Http) {
        this.http = http;
    }

    getFriends() {
        return this.http.get('friends.json')
            .toRx()
            .map(res => res.json());
    }
}

Here is the contents of our friends.json file, I’ve added another property to make it slightly more interesting than just an array of names.

[
    {
        "firstName": "Pablo",
        "gender": "M"
    },
    {
        "firstName": "Erica",
        "gender": "F"
    },
    {
        "firstName": "Lukas",
        "gender": "M"
    }
]

Now our friends-list component can be broken down further and we’ll take the display of the friend out into another component. Our DataService is still being injected into the constructor, but now instead of just using the array directly, we need to call subscribe (which is another Rx method) to assign the results to our friends property.

@Component({
    selector: 'friend',
    properties: ['person']
})
@View({
    template: '<div>{{ person.firstName }} ({{ person.gender }})</div>'
})
class FriendComponent {
    person = {firstName: 'Foo', gender: 'M'};
}

@Component({
    selector: 'friends-list',
    bindings: [DataService]
})
@View({
    template: `
        <div>
            <h2>Friends</h2>
            <friend *ng-for="#friend of friends" [person]="friend"></friend>
        </div>
    `,
    directives: [FriendComponent, NgFor]
})
class FriendsList {
    friends: Object[];

    constructor( @Inject(DataService) service: DataService) {
        service.getFriends().subscribe(res => {this.friends = res; });
    }
}

Lastly we add the HTTP_BINDINGS to our bootstrap method, and then our service will pull the data from the remote source.

bootstrap(App, [HTTP_BINDINGS])
    .catch(err => console.error(err));

Ready, Set, Go!

Working with alpha software is not for everyone. However, due to the popularity of Angular 1.x I think you can count on Angular 2 being important in the future. Even though the API is evolving and may be radically different by the time of the full release than right now, it’s good to get in at this early stage so that by the time that it does get released you’ll already be an expert. This is the best time to help mold the future of Angular as well, while it’s in an unrefined state. At the time of this writing the Angular Team is working hard towards a beta release. They are open to feedback and contributions, and pretty much the only way to come up with those is by using it.

I hope that you’ve enjoyed this tutorial and have some fun working with Angular 2. Please leave a comment below with any feedback or questions that you might have.

]]>
AngularJS for Beginners, Single-Page Applications Made Easy https://gamedevacademy.org/angularjs-for-beginners-single-page-applications-made-easy/ Tue, 09 Dec 2014 05:46:56 +0000 https://gamedevacademy.org/?p=2399 Read more]]> Upgrade your skills and become a more efficient developer by incorporating Angular.js, Google’s supported web application library, into your projects

In this course, you will learn how to use Angular.js from scratch so that you can create more user-friendly web applications, Single Page Applications (SPA), and interactive websites.

This course is taught by Pablo Farias Navarro, founder of ZENVAwith +50,000 students and hundreds of positive 5-star reviews.

What you will learn in this course.

  • How to use Angular.js to save time, create better projects and give your users a better experience.
  • We’ll create a full SPA from scratch (client side).
  • How to cloud-enable your SPA so that you can connect it to any kind of backend.
  • Fully commented source code of the course project.
  • Learn how to architecture a SPA: modules, controllers, services
  • Learn how to add URL routes to your client-side SPA.
  • We’ll be using Angular.js version 1.3.2.
  • Access live examples at the end of each coding lesson.
  • Learn how to use other great tools such as Boostrap 3, UnderscoreJS and Google Chrome’s Developer Tools!

Become a better web developer and start using Angular today in your existing and new projects. See you in the course :)

[button link=”https://academy.zenva.com/product/angularjs-for-beginners-single-page-applications-made-easy/?zva_src=gamedevacademy” target=”_blank” style=”none, small, large, biglarge” title=”ACCESS THE COURSE”][/button]

 

]]>