An open API service indexing awesome lists of open source software.

https://github.com/davepartner/angular2-tutorial-with-firebase-book


https://github.com/davepartner/angular2-tutorial-with-firebase-book

Last synced: 3 months ago
JSON representation

Awesome Lists containing this project

README

          

# Angular2 ebook

This book is currently being developed. Its not ready yet, but in this book, I'll be teaching how o
create an applicaion using Angular2 using several backend technologies starting with firebase. Your PR is highly welcome.

ANGULAR2 + Firebase 3 Tutorial
=================

###Who

I'm Dave Partner Ozoalor. I'm a software engineer & developer evangelist at [Davepartner.com](http://davepartner.com), and I've been teaching lots of programming languages on [Youtube](http://youtube.com/c/braintemorg).
And I want to teach you now.
Because you're good looking.
And because it's useful.

##What is AngularJs
Angularjs is an opensource javascript framework for build mobile and web applications using HTML and Javascript. Angularjs is managed by Google. Its widly rated as the most popular javascript framework for building mobile and web applications.

##What is Angular2
Angular2 is the second and latest version angularjs recently released by Google. Its much easier to learn and comes with many powerful features such as effective data management, HTTP services, form handling, fast template rendering and every other tool you need to build complex frontend web applications. You can also fuse any backend technologies you are good with into angular2 without any hassles such as firebase,couchdb, pouchdb, mongodb, nodejs and so on.
Angular2 was built with mobile devices first in mind which means it takes a mobile first approach.

##Audience
This book is written for novices and proffessionals who wish to learn how to build fast and scalable frontend applications for mobile and the web. This book will take your knowledge of Angular2 from basics to proffessional. Suitable examples will be used to describe aspects of angular2.

##Prerequisites
A BASIC understanding of the following will suffice:
* 1. HTML
* 2. CSS
* 3. Javascript .Angular2 uses a special kind of javascript called Typescript, that's what we will be treating first in this book so you do not need to know a lot of javascript to learn angular2.
* Knowledge of Angular 1 is NOT required. You can just jump right in and start learning how to build apps with angular2.

##Table of conents
* Text Editors
* Installation and Setup
* Nodejs Installation
* Angular CLI Installation
* Atom Text Editor Installation
* Install Typings
* Install Firebase
* Install Typscript definitions for Firebase
* Create New Angular 2 Project
* Start a server
* ES6/Typescript
* Variable declaration
* Classes
* Template Strings
* Arrow Functions
* Promises
* Components
* Inputs
* Outputs
* Lifecycle
* Pipes
* Services
* Templates
* Events
* Forms
* ViewChild

###Text Editors and IDEs

The first thing you'll need is an environment to write your code. There are many Integrated Developmemt Environments (IDE) you can use. However, the below are the ones I use.

* Your current IDE. If you have ever written any HTML code then you can keep using that IDE you used to write the code.
* [Notepad++](https://notepad-plus-plus.org/download/v7.2.html) - This is lightweight, simple and will get the job done.
* [Sublime Text ](https://www.sublimetext.com/download) - Really superb, lightweight and smart too.
* [Aptana Studio 3](http://aptana.com/)
* [Atom.io](https://atom.io/) - This is my new found love, it has really powerful features to make your code easy. I combine it with codelobster, link below.
* [CodeLobster](http://www.codelobster.com/download.html) - I really like this code editor when ever I am write html, css and javascript codes because of its amazing syntax highlighting and code folding that comes as default settings.
You just need one of the above listed IDEs.

There are many others [listed here](http://en.wikipedia.org/wiki/List_of_HTML_editors), you can check them out.

### Installation and setup
In this chapter we will be going through the installation and setup of our first angular 2 project. We will be making use of a fine combination of Nodejs and Angular-CLI as an easier and more effective way to build angular 2 applications.

#### Nodejs
The first thing we will be installing is called Nodejs. Nodejs is a platform for building fast and scalable applications. Its built on top of Chrome's powerful runtime.
To install Nodejs, visit [Nodejs.org](http://nodejs.org) and download the latest stable version and install it on your system. If you want to learn more about Nodejs at a later time, feel free to take my [Nodejs tutorial](https://www.youtube.com/watch?v=JoCoXXqBCvQ&list=PLnBvgoOXZNCPEEN6BtSu6O3yf0CDA7pjb) on youtube.

#### Angular-CLI
Angular-CLI stands for Angular command line interface, its a command line interface for building angular applications using nodejs style modules. Its easier, less noisy and more automatic than just building Angular apps from scratch. Angular-CLI takes the pain of manually creating files and typing out certain default codes off yoru shoulders.

Once your Nodejs installation is complete, open your command prompt and type `npm install -g angular-cli`.
If you don't know how to open your command prompt, just click on your windows start menu and type `cmd`, or type `node` then click on the windows command prompt that will show up.
When the window shows up, just type `npm install -g angular-cli`. If you have any errors, its probably because you have not installed nodejs or you have not restarted your system after the installation.

#### Create New Angular 2 Project
We will be using Angular-CLI to create our first angular2 project. To do that, navigate to the folder you'd like to create your angular project in and run this command on your command prompt `ng new angular2-blog`. After which you navigate into the project folder by running `cd angular2-blog`.
Note that `angular2-blog` is the name we want to give our new app. You can name yours anything. But the syntax remains `ng new {
// This fat arrow function binds to the current "this" context context. So this will print "Volvo"
console.log(this.carName);
});
}
}
```

### Classes in Typescript

Typescript leverages ES6 features to give developers the ability to use object-oriented class-based approach to building reusable components as the basic means of building up reusable components. This is as opposed to the traditional functions and prototype-based inheritance used in earlier versions of javascript.
Let's see a quick example here:

```
class Drive{
car: string;

constructor(carName : string){
this.car = carName;

this.aboutCar();
}

aboutCar(){
console.log("Your car name is " + this.car);
return this.car;
}

}

let drive = new Drive("Toyota");
```

As you can see above, we have a class named `Drive` with 3 members. We refer to each of the members using the `this` keyword. `this` denotes that its a member access.

In the example above, you may notice that we have accessed each member freely without using either the public, private or modifier. That is because in Typescript it is not required unlike in some languages such as C#. By default, all members in Typescript are public. Although you can still explicitly declare them as `public`. `private` or `protected`.

Example of the above code with members explicitly declared as public:
```
class Drive{
public car: string;

public constructor(carName : string){
this.car = carName;

this.aboutCar();
}

public aboutCar(){
console.log("Your car name is " + this.car);
return this.car;
}

}

let drive = new Drive("Toyota");
```
If you mark a member as `private`, it cannot be accessed from outside of its containing class

###Promises In Typescript
Typescript uses the concept of promises to provide a unique way to write asynchronous functions. Here is a good example of an attempt to fetch data froom an api, print the results or print the error.

```
loadListOfCars() {
fetch('goto/ourapi/cars').then((response) => {
return response.json(); //convert our resonse to json
}).then((data) => {
this.cars = data; //save it in a variable called this.cars
}).catch((error) => {
console.error('Error fetching users', error); //print any errors
});
}
```
We'll be seeing lots of usage of promises as we build our Angular 2 application, its very effective.

### Template Strings
This is not specifically Typescript, its more of an ES6 feature but its still worth including here because Angular2 implements it. ES6 gives you the ability to write long or multi-line inline strings which is not possible in the good old ES5 javascript without concatenation. Here is what I mean:

```
//In Javascript
var variable1 = 'I love Dave Partner\'s '+
'blackberry phones that are'+
'all good in color';
```
As you can see, we had to use concatenation to join each of the line in order to avoid errors. In Typescript, you'd just need to use back ticks, one at the beginning and one at the end. The back tick key is directly above the tab key on your keyboard. Here is the same code in Typescript:

```
var variable1 = `I love Dave Partner\'s
blackberry phones that are
all good in color`;
```

Here is another more detailed example with data binding:

```
let eatery_name = 'Dave Delicious';
let city_name = 'Dave Delicious';

let template = `


${eatery_name} Eatery



The best Eatery in the whole ${city_name} city.



`;
```
The way we will be using in this app will be making use of double curly bracelates example `{{ eatery_name }}`, instead of the example we used above `${eatery_name}`. This enables two-way data binding in Angular 2.

This brings us to the end of our Typescript journey, though what we've seen above is just a summary of the main parts of Typescript we'll be using in our Angular2 application. Let's continue with building our app in Angular2 while explaining basic concepts.

## Angular 2 Components
A component in Angular2 is just a combination of `.ts` file that contains a controller class which connect to its own `.html` view file and contains the logic that will be displayed in the view. In Angular2, everything is a component or component based. A component also connects to services NS Angular platform core libraries. Every component has a decorator.

When we created our Angular2 project above using the Angular-CLI command `ng new angualr-blog`, Angular-CLI also created a default component class for us. The component class is called `App Component`. App component is the root component of every angular2 app.
Every angular2 component has 4 files. Here is an example of the default app component that comes with new Angular2 files:

```
/.git
/e2e
/node_modules
/app/
|-app.component.ts - this is the file that contains the class
|-app.component.css - this contains the css for styles for the view
|-app.component.html - this contains the html for view
|-app.component.spec.ts - contains some defintions, you wont need to touch this file
```
Here is a typical component and how it relates to other parts of Angular2.
![image](https://cloud.githubusercontent.com/assets/1010556/20860116/ed0ffb86-b970-11e6-920f-31ac297ef0f4.png)
#### How to create a new component
To create a new component, just run `ng generate component ` or `ng g c ` for short. Since we are creating a blog app, let's create a `posts` component. This posts component will contain the list of blog posts. We'll create more components as we move along.
Run `ng g c posts`.
This will create a new `posts` folder inside `/app` and add files to it. Our folder structure will now look like this:
```
/.git
/e2e
/node_modules
/app/
|-posts/
|-post.component.ts
|-post.component.css
|-post.component.html
|-post.component.spec.ts
|-app.component.ts - this is the file that contains the class
|-app.component.css - this contains the css for styles for the view
|-app.component.html - this contains the html for view
|-app.component.spec.ts - contains some defintions, you wont need to touch this file
```

Nice!

Lets create more components we will be needing, run the following

`ng g c posts-add`
This will create a second `posts-add` component that we'll be using to add new posts to the blog.
This is what it looks like depicting it hierarchically.
![image](https://cloud.githubusercontent.com/assets/1010556/20860157/c8e3fcde-b971-11e6-8a24-79d1890e209e.png)

#### Parts of a component
An angular 2 component `.ts` file has different parts. We'll explain it using the generated code in `posts-add.component.ts`.

```
//posts-add.component.ts
//import section
import { Component, OnInit } from '@angular/core';

//decorator
@Component({
selector: 'app-posts-add',
templateUrl: './posts-add.component.html',
styleUrls: ['./posts-add.component.css']
})

//class
export class PostsAddComponent implements OnInit {

//constructor
constructor() {
first_name = 'Dave'; //I added this
}

ngOnInit() {
}

}
```

The main sections we will be explaining above are the `import` , `decorator`, `class` and `constructor` sections.

### Imports
The `import` section is always at the top of the page, usually the first in the `.ts` component file.
Its the section where the component imports all the libraries, services, classes and other components it needs to build the logic for display on the `.html` view file.

#### Decorator
The `decorator` function of the code defines the meta data for the class immediately below it. Decorators always start with `@` symbol. The decorator above defines the files where the css style and template is located, it also defines the html selector that represents this component.
Here is a full list of metadata properties that can be defined inside a decorator in Angular2, although we'll eventually be making use of just few key ones in this tutorial.
Angular2 Metadata Properties:
inputs - list of class property names to data-bind as component inputs
interpolation - custom interpolation markers used in this component's template
moduleId - ES/CommonJS module id of the file in which this component is defined
styleUrls - list of urls to stylesheets to be applied to this component's view
styles - inline-defined styles to be applied to this component's view
template - inline-defined template for the view
animations - list of animations of this component
changeDetection - change detection strategy used by this component
encapsulation - style encapsulation strategy used by this component
entryComponents - list of components that are dynamically inserted into the view of this component
exportAs - name under which the component instance is exported in a template
host - map of class property to host element bindings for events, properties and attributes
templateUrl - url to an external file containing a template for the view
viewProviders - list of providers available to this component and its view children
outputs - list of class property names that expose output events that others can subscribe to
providers - list of providers available to this component and its children
queries - configure queries that can be injected into the component
selector - css selector that identifies this component in a template

The `class` functions just like a normal class in Java or C#, its just a collection of objects. The class has a constructor function that runs by default once you the class is instantiated. The class also has an `export` statement that makes sure the class can be `imported` in any other component and used, just like we saw in the `import` section description above.

The ngOnInit() function fires everytime the component is called. As you can see, `OnInit` is also imported in the importsection from `angular/core`.
Like so:
`import { Component, OnInit } from '@angular/core';`

#### Data Flow (Into the View)
Angular enables the use of a powerful feature called two-way data binding. This simply means that data can be passed from the view to the controller and back in real-time.
Inside the constructor class we declared a variable called `first_name`and assigned the value of `Dave` to it. This variable is also accessible from the `.html` file of a component with no extra effort on your part. That's the power of angular2.
Let's see what's in the `posts-add.component.html` and how the variable can be used there.

```
//src/app/posts-add/posts-add.component.html


posts-add works!


```
####String Interpolation
The above is just a basic html, when the component is called, it should just print `post-add works!`. Lets just add the variable we declared in the component class in `posts-add.component.ts`. To do that we just need to put the variable in double curly bracelets `{{first_name}}`
```
//src/app/posts-add/posts-add.component.html


{{first_name}} posts-add works!


```
####Property Binding
There is another method called `Property binding` which we will see when we start treating forms. Here is what it looks like
``.
That `expression` will result to `true` or `false`.
Property binding can be done on
* HTML properties, for example the `value` property.
`[value]="expression"`.
* In-built Angular directives such as `[ngClass]="expression"`
* Custom made properties such as `[whateverProperty]="expression"`

Let's see a practical example which also applies to all the other types of binding discussed in this section.
Go to `src/app/posts-add/posts-add.component.ts` and declare some variables for the form we'll use to create new posts.

My `src/app/posts-add/posts-add.component.ts` now looks like this:
```
import { Component, OnInit } from '@angular/core';

@Component({
selector: 'app-posts-add',
templateUrl: './posts-add.component.html',
styleUrls: ['./posts-add.component.css']
})
export class PostsAddComponent implements OnInit {

postTitle = "The quick brown fox "; //added this
postDescription = "Jumps over lorem Ipsum fox mesit"; //added this

constructor() { }

ngOnInit() {
}

//added the below
addNewPost(){
//method to exectute when the submit button is clicked
}
}
```

Go to `src/app/posts-add/posts-add.component.html` and create a HTML form using `[(ngModel)]` to bind the data declared in `src/app/posts-add/posts-add.component.ts` to the views.
My `src/app/posts-add/posts-add.component.html` now looks like this:

```

Create new post

Post Title

Description

Sign in

```
Take note of the `[(ngModel)]="postDescription"` and the `[(ngModel)]="postTitle"`, the values of the properties are the same as the variable names declared in `src/app/posts-add/posts-add.component.ts`.
The effect of the above two-way data binding is that when the user visits the posts-add page, the textbox will be automatically filled with `The quick brown fox` while the textarea will contain `Jumps over lorem Ipsum fox mesit`.
We will see more of this in action further down the turtorial.

####Two-way data binding
We can use two-data binding in form elements in angular2 by assigning it to `[(ngModel)]` attribute. For instance:

While `username` is a variable already declared in the `.ts` file.

####Event Binding
You can bind events in angular2 like so ``. This is an example of an onclick() event and what expression or function will be exectuted when it is called.

To inject the code of one `.html` file into another, you have to:
* First: Import the component class into the `.ts` file of the new component you'd like to inject it into.
Here is the syntax:
`import {ClassOfOldComponent} from '';`

* Second: place the html-selector of the old component inside the html of the new component.
Don't worry, we'll see this in practice as we build a blog.

Since we are building a blog, let's insert the contents of the `posts-add.component.html` into `app.component.html`. This is because `app.component.html` is the default component displayed when you visit your homepage. Your homepage is proabably located at `localhost:4200` when you visit on your browser.

```
srs/app/app.components.ts
import { Component } from '@angular/core';
import {PostsAddComponent} from './posts-add/posts-add.component'; //I just added this, it just imports posts-add component class into app.component.ts to be used

//the rest of this file goes here
```

Then go to the html and add ` Loading`
```
srs/app/app.components.html


Home works!

Loading

```

That's how to use one component into another. You can inject multiple components into others with no limitation. We'll use it as we build a blog further down the book.

### Adding Custom Assets
#### Twitter Bootstrap To Your Project
Bootstrap is a HTML,CSS and Javascript framework for designing beautiful and responsive user interfaces in web and mobile applications. It makes sense that we use it in this project instead of writing our own custom css from scratch.
We'll be using [Twitter bootstrap](http://getbootstrap.com) to style our blog to make it beautiful.
To do this, visit http://getbootstrap.com/getting-started/ , scroll down to the `Bootstrap CDN` section and copy the 3 stylesheet and javascript links there. Then paste it anywhere inbetween the section of your `src/index.html` file.
Bootstrap also needs Jquery to function properly, so add jquery too by visiting https://code.jquery.com/ . On the page, select 'minified' version of the jquery version you want, then copy the code that pops up. I selected the minified version of Jquery version 3.x .
Paste the code you copied at the bottom of your `index.html` file, just before the closing `
Loading...




` tag of `src/index.html`. I'll also add a footer. Update the file to look like this:

```



Loading...


© 2016 Company, Inc.






```

The above will show a blank page with a black top navigation bar and a login form. Next, we head over to `src/app/app.component.ts` and change its content to the following code.

```



Hello, world!


Welcome to our first Angular2 blog. Please find our blog posts below.


Learn more »




Loading...

```

app.component is basically the root component of the application, that is to say, if you stack all the components one on top the other, the app.component will be at the top.
* Notice that we are importing the contents of `src/app/home/home.components.html`.

So let's head over to `src/app/home/home.components.html` and insert some code. The code we will insert will be a dummy code that will eventually list the latest blog posts when we connect this application to a database. If you have not created `home.component` you can create it by running `ng g c home` on your cmd. Or you can use the `post component` we created ealier for this purpose. We just need to list the latest posts with a short description each.
So open `src/app/home/home.components.html` and change the code there to:

```



Heading


Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui.


View details »




Heading


Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui.


View details »




Heading


Donec sed odio dui. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Vestibulum id ligula porta felis euismod semper. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.


View details »




```

That settled, run `ng serve` and view your app on your browser by visiting `localhost:4200` . You should see a beautiful but static blog.
Here is what mine looks like:

![image](https://cloud.githubusercontent.com/assets/1010556/20647101/8179b342-b48b-11e6-8fb9-601ebda37b5c.png)

##Ng-Content Directive
This is a way that Angular2 makes sure that the initial content of your component's selector does not get overwritten when the component's content gets loaded.
Normally, if you had `Loading... `. The `loading...` will be replaced by whatever is located in `src/app/home/home.component.html` when it is loaded. If you dont want this replacement to happen, but wish to display both contents at the same time, you'll need to go to `src/app/home/home.component.html` and enter the tag ` ` at any part of the code you wish the contents of `Loading... ` to be displayed.
Its as simple as that - go to the component and tell it where to append the initial contents of its selector.

##Routing and Navigation
Routing and Navigation in Angular2 is quite simple. You just have to import `import { RouterModule, Routes } from '@angular/router';` into `src/app/app.module.ts`. Then define your route parameters in a variable of the type `Routes`. Let's see a practical example.

Update your `src/app/app.module.ts` to the below, lookout for the comments I added.
```
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { PostsAddComponent } from './posts-add/posts-add.component';

//added
import { RouterModule, Routes } from '@angular/router';

//added: declare the route parameters below
const appRoutes: Routes = [
{ path: 'posts-add', component: PostsAddComponent },
{ path: 'posts-view/:id', component: PostsViewComponent },
{ path: '', component: HomeComponent },
{ path: '**', component: PageNotFoundComponent }
];

//added: RouterModule.forRoot(appRoutes) in the imports:[...] section below
@NgModule({
declarations: [
AppComponent,
HomeComponent,
PostsAddComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule.forRoot(appRoutes)
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

```
* `import { RouterModule, Routes } from '@angular/router';` - This imports the needed modules for the routing to take place.
* `const appRoutes: Routes= [...]` - This section defines the route parameters, that is, which url redirects to which page. If you have more components you will simply add them to this array. But be sure to have created the page first. Angular-CLI wil automatically import the page into this file after you have created it, otherwise you'll get an error promoting you to import it yourself.
* `RouterModule.forRoot(appRoutes)` - This imports the defined parameters using the RouterModule imported in the beginning.
* `{ path: '**', component: PageNotFoundComponent }` -This line specifies the component that will be loaded if a route not specified is visited. This is perfect for creating 404 not found pages. Go to your command prompt and create the `page-not-found` component. Navigatge to the `.html` file of the component and type the error people will see if they visit a page that does not exist in your app.

If we wanted to send other parameters along with the url, you can use the `data` property. The route parameters will look something like this:

```
{
path: '/user/dave',
component: DaveComponent,
data: {
first_name: 'Dave',
middle_name: 'Partner',
networth: '$17b'
}
}
```

If you serve this on your browser at this point, you'll get an error. You need to complete one more step. You need to tell angularjs where to insert the contents of the new component whenever its loaded.
So go to your `src/app/app.components.html` and change `Loading...` to `` .That all.

Here is what my new `src/app/app.components.html` looks like now:
```



Hello, world!


Welcome to our first Angular2 blog. Please find our blog posts below.


Learn more »






```
To add a clickable link in Angular2, you just need to two angular2 attributes
* `routerLink` - Angular2 does not make use of `href`, so `routerLink` is the attribute for specifying the address to be loaded.
* `routerLinkActive` - This is optional, its a way to specify the css selector properties to apply when the link is active. In the example below we are going to assume that we have written a css class with the name `activeLink`.

Let's add some clickable links to the top navigation bar of this app. Go to `src/index.html`, scroll to the ``, locate the line that reads `