{"id":19529375,"url":"https://github.com/davepartner/angular2-tutorial-with-firebase-book","last_synced_at":"2026-03-04T10:03:14.636Z","repository":{"id":110556040,"uuid":"73466358","full_name":"davepartner/angular2-tutorial-with-firebase-book","owner":"davepartner","description":null,"archived":false,"fork":false,"pushed_at":"2017-01-02T12:31:22.000Z","size":60,"stargazers_count":0,"open_issues_count":0,"forks_count":2,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-02-26T02:42:10.519Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/davepartner.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2016-11-11T09:57:47.000Z","updated_at":"2020-06-20T14:11:06.000Z","dependencies_parsed_at":"2023-03-26T02:18:22.835Z","dependency_job_id":null,"html_url":"https://github.com/davepartner/angular2-tutorial-with-firebase-book","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/davepartner/angular2-tutorial-with-firebase-book","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/davepartner%2Fangular2-tutorial-with-firebase-book","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/davepartner%2Fangular2-tutorial-with-firebase-book/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/davepartner%2Fangular2-tutorial-with-firebase-book/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/davepartner%2Fangular2-tutorial-with-firebase-book/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/davepartner","download_url":"https://codeload.github.com/davepartner/angular2-tutorial-with-firebase-book/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/davepartner%2Fangular2-tutorial-with-firebase-book/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":30078307,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-03-04T08:01:56.766Z","status":"ssl_error","status_checked_at":"2026-03-04T08:00:42.919Z","response_time":59,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-11T01:24:32.209Z","updated_at":"2026-03-04T10:03:09.626Z","avatar_url":"https://github.com/davepartner.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# Angular2 ebook\n\nThis book is currently being developed. Its not ready yet, but in this book, I'll be teaching how o \ncreate an applicaion using Angular2 using several backend technologies starting with firebase.  Your PR is highly welcome.\n\n\n\n\nANGULAR2 + Firebase 3 Tutorial\n=================\n\n###Who\n\nI'm Dave Partner Ozoalor.  I'm a software engineer \u0026 developer evangelist at [Davepartner.com](http://davepartner.com), and I've been teaching lots of programming languages on [Youtube](http://youtube.com/c/braintemorg). \nAnd I want to teach you now.\nBecause you're good looking.\nAnd because it's useful.\n\n##What is AngularJs\nAngularjs 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.\n\n##What is Angular2\nAngular2 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.  \nAngular2 was built with mobile devices first in mind which means it takes a mobile first approach.\n\n##Audience\nThis 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.\n\n##Prerequisites\nA BASIC understanding of the following will suffice:\n* 1. HTML\n* 2. CSS\n* 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. \n* Knowledge of Angular 1 is NOT required. You can just jump right in and start learning how to build apps with angular2.\n\n\n##Table of conents\n* Text Editors\n* Installation and Setup \n\t* Nodejs Installation\n\t* Angular CLI Installation\n\t* Atom Text Editor Installation\n\t* Install Typings\n\t* Install Firebase\n\t* Install Typscript definitions for Firebase\n\t* Create New Angular 2 Project\n\t* Start a server\n* ES6/Typescript\n\t* Variable declaration\n\t* Classes\n\t* Template Strings\n\t* Arrow Functions\n\t* Promises\n* Components\n* Inputs\n* Outputs\n* Lifecycle\n* Pipes\n* Services\n* Templates\n* Events\n* Forms\n* ViewChild\n\n###Text Editors and IDEs\n\nThe 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.  \n\n * Your current IDE. If you have ever written any HTML code then you can keep using that IDE you used to write the code.\n * [Notepad++](https://notepad-plus-plus.org/download/v7.2.html) - This is lightweight, simple and will get the job done. \n * [Sublime Text ](https://www.sublimetext.com/download) - Really superb, lightweight and smart too.\n * [Aptana Studio 3](http://aptana.com/) \n * [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.\n * [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.\nYou just need one of the above listed IDEs. \n\nThere are many others [listed here](http://en.wikipedia.org/wiki/List_of_HTML_editors), you can check them out.\n\n### Installation and setup\nIn 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. \n\n#### Nodejs \nThe 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. \nTo 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\u0026list=PLnBvgoOXZNCPEEN6BtSu6O3yf0CDA7pjb) on youtube.\n\n#### Angular-CLI\nAngular-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. \n \nOnce your Nodejs installation is complete, open your command prompt and type `npm install -g angular-cli`. \nIf 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. \nWhen 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.\n\n#### Create New Angular 2 Project\nWe 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`.\nNote that `angular2-blog` is the name we want to give our new app. You can name yours anything. But the syntax remains `ng new \u003cname of project`.\nIn case you don't know how to navigate to the correct project folde using your command line, here is how to do it:\nopen your command prompt and type `cd \u003cpath to project directory`. For me, since I want to create my project on my desktop, I'll simply type `cd C:\\Users\\dell\\Desktop\\`. Then hit enter. \n\n#### Typings \nTypings is a definition manager for Typescript, it helps you install Typescript definitions. Typings makes use of a file named typings.json that resolve to the Typings NPM, Bower, Registry, GitHub, HTTP and local files. Packages can use type definitions from various sources and different versions without conflict.\nSo install Typings by typing `npm install -g typings`. \n\n#### Firebase \nFirebase is a backend as a service that can be plugged into any application and any platform. Firebase contains a bundle of packages most apps need some of which are notification system, NoSql database, crash reports, admob, user authentication system and so on. Angular 2 just builds the frontend of your app for you, we will still need a backend to handle the above. We will be using firebase in this tutorial. Other alternatives of firebase are MongoDB database, One signal notification, couchDB and so on. As you can see it is hard to find it all in one bundle like firebase did. \nThe only real downside of Firebase is that your app cant function offline like some mobile apps may need such as game and notepad.\nWe'll be needing Firebase further down the tutorial but let's just install it now.\n\nSo open your command prompt, navigate to your project folder if you are not already there and type `npm install --save firebase`. \nThis installs firebase into your project. We also need to typings for Firebase.\n\nTo install Typings definition for Firebase run `typings install --save firebase` on your command prompt, be sure you are still in the project folder. \nYou can read more about Firebase  [here on npm](https://www.npmjs.com/package/firebase) and their official [Firebase documentation](https://firebase.google.com/docs/).  \n\n#### Viewing your app\nTo view the app we need to spin up a server. To do that, be sure you are on your projects folder, run `ng serve`. Your server will come up and and display the url you can use to view the app on your browser. Mine is `http://localhost:4200/`. Copy it and paste in your browser then hit enter.\n\n####Installations summary\n1.  Download and Install Nodejs from http//nodejs.org\n* Open a command prompt (cmd) on your computer by clicking on your start menu and typing (running) `cmd` then hit enter. \n* When the cmd window opens, type `node -v` and hit enter. If it shows you a version of nodejs, then nodejs was correctly installed.\n2. Install Angular-CLI\n* In your command prompt window, run `npm install -g angular-cli`\n3. Create new Angular2 project, \n* First navigate to any folder in your computer you want to create the project in. Mine is on my desktop. So to navigate to my desktop, I'd run `cd C:\\Users\\dell\\Desktop\\angular projects`. \n* After which I'd run `ng new angular2-blog` to create new angular2 project I decided to name `angular2-blog`. \n\nOther things you can install are Firebase and Typings as outlined above. \n\n## Introduction to ES6/Typescript\nTypescript is a new powerful programming language built and maintained by Microsoft, it is a superset of javascript and comes with very powerful features such as static typing and class-based object-oriented programming. Google chose to build Angular2 on Typescript instead of its other alternatives such as babel, atScript and Dart. Angular 2 uses TypeScript because it improves developer productivity because of its types. \nIf you prefer to work with javascript instead you can visit Angular2's official documentation section and gain access Angular2 documentation for javascript and [Dart](https://angular.io/docs/dart/latest/index.html) although I wouldn't recommend this.\n\nES6 is the next version of JavaScript that was just recently approved. It comes with a ton of new ways to write JS. However, its downside is that it has not been fully implemented by many browsers. ES7 is also in the pipeline. \nMost browsers only understand javascript upto ES5, which is the normal javascript most people code. When building angular2 applications with typescript (ES6), your browser still needs to have the code compiled to ES5 javascript before it can understand it. There are two main transpilers that do this job:\n* [Traceur](https://github.com/google/traceur-compiler) - Owned by Google\n* [Babeljs](https://babeljs.io/) - Babel is more popular \n\nWe are taking time to explain most of these terminologies here in the beginning so that when we start writing actual code, it will be less boring because we won't have much explanations to make. We'll go through a quick typescript tutorial just to familiarize you with the code we'll be writing for the rest of this tutorial.\n\n### Variable Declaration in Typescript\nVAR in ES5 javascript, variables are declared with the `var` keyword. The problem is that this keyword does not properly scope the variables. A good example is when you declare a variable in a loop you are using. The variable may sometimes still be available after the loop thereby pottentially messing up your whole code. Below is an example:\n``` \nfor (var j = 0; j \u003c= 1; j++){\n\t//j is available here\n}\n//unfortunately, j is also available here\n```\n\nLET in Typescript,  in Typescript, variables are declared with the `let` keyword, forcing them to stay available only within the scope they are defined in. This prevents that unnecessary overflow, and is perfect for functions and closures. Let's look at the above function once again using let.\n```  \nfor (let j = 0; j \u003c= 1; j++){\n\t//j is available here\n}\n// J is not available here\n\n```\nNice! So its adviced you use `let` whenever necessary. \n\n### Function Types in Typescript\nIn Typescript, function paramters need to be typed and are all required by default. Below is an example of a function that takes in 3 parameters `firstname` , `middlename` and `lastname`.\n\n```\nfunction fullname(firstname : string, middlename = \"partner\", lastname? : string){\n      \n      //firstname = required\n      //middlename = will resolve to 'partner' if not provided when the function is being called\n      //lastname = optional because of the '?' sign right after the parameter\n      //they all bear the type 'string'.\n\n}\n```\n* Note that, required parameters must come before the optional parameters. if we wanted firstname to be optional,we would have to exchange its position withe `middlename` since middle name has a default value. \n\nFrom the above, here are valid ways to call the above function:\n```\nfullname(\"Dave\") //correct\nfullname(\"Dave\", \"Young\") // correct\nfullname(\"Dave\", \"Young\" , \"Money\") //correct\nfullname(undefined,\"Young\") //correct\nfullname() //error, too few parameters\nfullname(\"Dave\",\"Young\", \"Money\", \"Xing\") //error, too many parameters\n```\nThere are a couple of other tweaks to note in Typescript functions, but we will not cover them all here since this is not primarily a typescript function.\n\n####Arrow functions \nFat arrow functions in Typescript helps write shorter cleaner functions. Here is a comparison between a function written anonymously and the same function replicated with Typescripts fat arrow.\n\n```\n//\nclass Car {\n  constructor() {\n    this.carName = 'Volvo';\n    \n    \tvar that = this;\n\tsetTimeout(function() {\n\t  console.log(that.name); //we used \"that\" to make reference to the outer \"this\" context\n\t});\n  }\n}\n```\nLet's see this same function in Typescript:\n\n```\n//Typescript\nclass Car {\n  constructor() {\n    this.carName = 'Volvo';\n    \n    setTimeout(() =\u003e {\n      // This fat arrow function binds to the current \"this\" context context. So this will print \"Volvo\"\n      console.log(this.carName);\n    });\n  }\n}\n```\n\n### Classes in Typescript\n\nTypescript 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. \nLet's see a quick example here:\n\n```\nclass Drive{\n\tcar: string;\n\t\n\tconstructor(carName : string){\n\t\tthis.car = carName;\n\t\t\n\t\tthis.aboutCar();\n\t}\n\t\n\taboutCar(){\n\tconsole.log(\"Your car name is \" + this.car);\n\t\treturn this.car; \n\t}\n\n}\n\nlet drive = new Drive(\"Toyota\");\n```\n\nAs 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.\n\nIn 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`.\n\nExample of the above code with members explicitly declared as public:\n```\nclass Drive{\n\tpublic car: string;\n\t\n\tpublic constructor(carName : string){\n\t\tthis.car = carName;\n\t\t\n\t\tthis.aboutCar();\n\t}\n\t\n\tpublic aboutCar(){\n\tconsole.log(\"Your car name is \" + this.car);\n\t\treturn this.car; \n\t}\n\n}\n\nlet drive = new Drive(\"Toyota\");\n```\nIf you mark a member as `private`, it cannot be accessed from outside of its containing class\n\n\n###Promises In Typescript\nTypescript 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.\n\n```\nloadListOfCars() {\n  fetch('goto/ourapi/cars').then((response) =\u003e {\n    return response.json(); //convert our resonse to json\n  }).then((data) =\u003e {\n    this.cars = data; //save it in a variable called this.cars\n  }).catch((error) =\u003e {\n    console.error('Error fetching users', error); //print any errors\n  });\n}\n```\nWe'll be seeing lots of usage of promises as we build our Angular 2 application, its very effective.\n\n\n### Template Strings\nThis 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:\n\n```\n//In Javascript \nvar variable1 =  'I love Dave Partner\\'s '+\n                 'blackberry phones that are'+\n\t\t 'all good in color';\n```\nAs 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:\n\n```\nvar variable1 =  `I love Dave Partner\\'s \n                 blackberry phones that are\n\t\t all good in color`;\n```\n\nHere is another more detailed example with data binding:\n\n```\nlet eatery_name = 'Dave Delicious';\nlet city_name = 'Dave Delicious';\n\nlet template = `\n  \u003cdiv\u003e\n    \u003ch2\u003e${eatery_name} Eatery\u003c/h2\u003e\n    \u003cp\u003e\n      The best Eatery in the whole ${city_name} city.\n    \u003c/p\u003e\n  \u003c/div\u003e\n`;\n ```\nThe 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.\n\nThis 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. \n\n\n## Angular 2 Components\nA 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.\n\nWhen 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. \nEvery angular2 component has 4 files. Here is an example of the default app component that comes with new Angular2 files: \n\n```\n/.git\n/e2e\n/node_modules\n/app/\n\t|-app.component.ts - this is the file that contains the class\n\t|-app.component.css - this contains the css for styles for the view\n\t|-app.component.html - this contains the html for view \n\t|-app.component.spec.ts - contains some defintions, you wont need to touch this file\n```\nHere is a typical component and how it relates to other parts of Angular2.\n![image](https://cloud.githubusercontent.com/assets/1010556/20860116/ed0ffb86-b970-11e6-920f-31ac297ef0f4.png)\n#### How to create a new component\nTo create a new component, just run `ng generate component \u003ccomponent name\u003e` or `ng g c \u003ccomponent name\u003e` 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. \nRun `ng g c posts`. \nThis will create a new `posts` folder inside `/app` and add files to it. Our folder structure will now look like this:\n```\n/.git\n/e2e\n/node_modules\n/app/\n\t|-posts/\n\t\t|-post.component.ts\n\t\t|-post.component.css\n\t\t|-post.component.html\n\t\t|-post.component.spec.ts\n\t|-app.component.ts - this is the file that contains the class\n\t|-app.component.css - this contains the css for styles for the view\n\t|-app.component.html - this contains the html for view \n\t|-app.component.spec.ts - contains some defintions, you wont need to touch this file\n```\n\nNice!\n\nLets create more components we will be needing, run the following\n\n`ng g c posts-add`\nThis will create a second `posts-add` component that we'll be using to add new posts to the blog.\nThis is what it looks like depicting it hierarchically. \n![image](https://cloud.githubusercontent.com/assets/1010556/20860157/c8e3fcde-b971-11e6-8a24-79d1890e209e.png)\n\n\n#### Parts of a component\nAn angular 2 component `.ts` file has different parts. We'll explain it using the generated code in `posts-add.component.ts`.\n\n```\n//posts-add.component.ts\n//import section\nimport { Component, OnInit } from '@angular/core';\n\n\n//decorator\n@Component({\n  selector: 'app-posts-add',\n  templateUrl: './posts-add.component.html',\n  styleUrls: ['./posts-add.component.css']\n})\n\n//class\nexport class PostsAddComponent implements OnInit {\n\n//constructor\n  constructor() {\n  \tfirst_name = 'Dave'; //I added this\n  }\n\n  ngOnInit() {\n  }\n\n}\n```\n\nThe main sections we will be explaining above are the `import` , `decorator`, `class` and `constructor` sections.\n\n### Imports\nThe `import` section is always at the top of the page, usually the first in the `.ts` component file. \nIts 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. \n\n#### Decorator\nThe `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. \nHere 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. \nAngular2 Metadata Properties:\ninputs - list of class property names to data-bind as component inputs\ninterpolation - custom interpolation markers used in this component's template\nmoduleId - ES/CommonJS module id of the file in which this component is defined\nstyleUrls - list of urls to stylesheets to be applied to this component's view\nstyles - inline-defined styles to be applied to this component's view\ntemplate - inline-defined template for the view\nanimations - list of animations of this component\nchangeDetection - change detection strategy used by this component\nencapsulation - style encapsulation strategy used by this component\nentryComponents - list of components that are dynamically inserted into the view of this component\nexportAs - name under which the component instance is exported in a template\nhost - map of class property to host element bindings for events, properties and attributes\ntemplateUrl - url to an external file containing a template for the view\nviewProviders - list of providers available to this component and its view children  \noutputs - list of class property names that expose output events that others can subscribe to\nproviders - list of providers available to this component and its children\nqueries - configure queries that can be injected into the component\nselector - css selector that identifies this component in a template\n\nThe `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.\n\nThe  ngOnInit() function fires everytime the component is called. As you can see, `OnInit` is also imported in the importsection from `angular/core`. \nLike so:\n`import { Component, OnInit } from '@angular/core';`\n\n\n#### Data Flow (Into the View)\nAngular 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.\nInside 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. \nLet's see what's in the `posts-add.component.html` and how the variable can be used there.\n\n```\n//src/app/posts-add/posts-add.component.html\n\u003cp\u003e\n  posts-add works!\n\u003c/p\u003e\n```\n####String Interpolation\nThe 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}}`\n```\n//src/app/posts-add/posts-add.component.html\n\u003cp\u003e\n  {{first_name}} posts-add works!\n\u003c/p\u003e\n```\n####Property Binding\nThere is another method called `Property binding` which we will see when we start treating forms. Here is what it looks like \n`\u003cinput [required]='expression'/\u003e`.\nThat `expression` will result to `true` or `false`. \nProperty binding can be done on \n* HTML properties, for example the `value` property.\n`[value]=\"expression\"`.\n* In-built Angular directives such as `[ngClass]=\"expression\"`\n* Custom made properties such as `[whateverProperty]=\"expression\"`\n\nLet's see a practical example which also applies to all the other types of binding discussed in this section.\nGo to `src/app/posts-add/posts-add.component.ts` and declare some variables for the form we'll use to create new posts.\n\nMy `src/app/posts-add/posts-add.component.ts` now looks like this:\n```\nimport { Component, OnInit } from '@angular/core';\n\n@Component({\n  selector: 'app-posts-add',\n  templateUrl: './posts-add.component.html',\n  styleUrls: ['./posts-add.component.css']\n})\nexport class PostsAddComponent implements OnInit {\n\n  postTitle = \"The quick brown fox \"; //added this\n  postDescription = \"Jumps over lorem Ipsum fox mesit\"; //added this\n\n  constructor() { }\n\n  ngOnInit() {\n  }\n\n//added the below\n  addNewPost(){\n    //method to exectute when the submit button is clicked\n  }\n}\n```\n\nGo 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.\nMy `src/app/posts-add/posts-add.component.html` now looks like this:\n\n```\n\u003cform \u003e\n      \u003ch2\u003eCreate new post\u003c/h2\u003e\n\n      \u003clabel for=\"postTitle\"\u003ePost Title\u003c/label\u003e\n      \u003cinput  [(ngModel)]=\"postTitle\" type=\"text\" id=\"postTitle\" class=\"form-control\" placeholder=\"Title\" required autofocus\u003e\n\n      \u003clabel for=\"postDescription\" class=\"sr-only\"\u003eDescription\u003c/label\u003e\n      \u003ctextarea  [(ngModel)]=\"postDescription\"  id=\"postDescription\" class=\"form-control\" rows=\"5\"  placeholder=\"Description\" required\u003e \u003c/textarea\u003e\n\n      \u003cbutton class=\"btn btn-lg btn-primary btn-block\" type=\"submit\" (click)=\"addNewPost()\"\u003eSign in\u003c/button\u003e\n    \u003c/form\u003e\n\n\n```\nTake 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`.\nThe 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`.\nWe will see more of this in action further down the turtorial.\n\n\n####Two-way data binding\nWe can use two-data binding in form elements in angular2 by assigning it to `[(ngModel)]` attribute. For instance:\n\n\u003cinput type=\"text\" [(ngModel)]='username' /\u003e\n\nWhile `username` is a variable already declared in the `.ts` file.\n\n####Event Binding\nYou can bind events in angular2 like so `\u003cbutton (click)=\"expression/function\" /\u003e`. This is an example of an onclick() event and what expression or function will be exectuted when it is called.\n\n\nTo inject the code of one `.html` file into another, you have to:\n* First: Import the component class into the `.ts` file of the new component you'd like to inject it into. \nHere is the syntax: \n`import {ClassOfOldComponent} from '\u003cpath to where the .ts file is located\u003e';`\n\n* Second: place the html-selector of the old component inside the html of the new component. \nDon't worry, we'll see this in practice as we build a blog.\n\nSince 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.\n\n\n```\nsrs/app/app.components.ts \nimport { Component } from '@angular/core';\nimport {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\n\n//the rest of this file goes here\n```\n\nThen go to the html and add `\u003capp-posts-add\u003e Loading\u003c/app-posts-add\u003e`\n```\nsrs/app/app.components.html\n\u003ch1\u003e\nHome works!\n\u003c/h1\u003e\n\n\u003capp-posts-add\u003e Loading\u003c/app-posts-add\u003e  \u003c!--here is the selector for posts-add.component.html. The compiler will simply replace \u003capp-posts-add\u003e Loading \u003c/app-posts-add\u003e with the html contents in posts-add.components.html --\u003e\n\n```\n\nThat'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. \n\n\n### Adding Custom Assets\n#### Twitter Bootstrap To Your Project\nBootstrap 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. \nWe'll be using [Twitter bootstrap](http://getbootstrap.com) to style our blog to make it beautiful. \nTo 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 \u003chead\u003e \u003c/head\u003e section of your `src/index.html` file. \nBootstrap 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 . \nPaste the code you copied at the bottom of your `index.html` file, just before the closing `\u003c/body\u003e` tag.\n\nHere is mine, pay attention to the comments\n\n```\nlocated at src/index.html\n\u003c!doctype html\u003e\n\u003chtml\u003e\n\u003chead\u003e\n  \u003cmeta charset=\"utf-8\"\u003e\n  \u003ctitle\u003eAngular2Blog\u003c/title\u003e\n  \u003cbase href=\"/\"\u003e\n\n  \u003cmeta name=\"viewport\" content=\"width=device-width, initial-scale=1\"\u003e\n  \u003clink rel=\"icon\" type=\"image/x-icon\" href=\"favicon.ico\"\u003e\n\n  \u003c!-- I added the below --\u003e\n  \u003clink rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\" integrity=\"sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u\" crossorigin=\"anonymous\"\u003e\n  \u003clink rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css\" integrity=\"sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp\" crossorigin=\"anonymous\"\u003e\n  \u003cscript src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\" integrity=\"sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa\" crossorigin=\"anonymous\"\u003e\u003c/script\u003e\n\n\u003c/head\u003e\n\u003cbody\u003e\n  \u003capp-root\u003eLoading...\u003c/app-root\u003e \u003c!--this inserts the contents of app.component.html into this index.html page --\u003e\n  \n  \u003c!--added Jquery too below --\u003e\n  \u003cscript\n  src=\"https://code.jquery.com/jquery-3.1.1.min.js\"\n  integrity=\"sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=\"\n  crossorigin=\"anonymous\"\u003e\u003c/script\u003e\n  \n\u003c/body\u003e\n\u003c/html\u003e\n\n```\n\nNice, we are now good to go. We can now start using bootstrap and jquery UI features.  If you do not know how to use bootstrap, you can [checkout my boostrap tutorial on youtube] (https://www.youtube.com/playlist?list=PLnBvgoOXZNCMXAQ3FTgExmqYCzkfKKYDD).\n\n#### Designing the homepage\nYou can design your homepage using your usual HTML, CSS and Javascript. Since we are now using bootstrap in the project, I'll just build it all out using boostraps styles and classes. \nSince all all our pages will contain A top navigation bar, lets add it right under the opening `\u003cbody\u003e` tag of `src/index.html`. I'll also add a footer. Update the file to look like this:\n\n```\n\u003cbody\u003e\n  \u003cnav class=\"navbar navbar-inverse navbar-fixed-top\"\u003e\n      \u003cdiv class=\"container\"\u003e\n        \u003cdiv class=\"navbar-header\"\u003e\n\n          \u003ca class=\"navbar-brand\" href=\"#\"\u003e \u003ci class=\"glyphicon glyphicon-list-alt\"\u003e \u003c/i\u003e Angular2 Blog\u003c/a\u003e\n        \u003c/div\u003e\n        \u003cdiv id=\"navbar\" class=\"navbar-collapse collapse\"\u003e\n          \u003cform class=\"navbar-form navbar-right\"\u003e\n            \u003cdiv class=\"form-group\"\u003e\n              \u003cinput type=\"text\" placeholder=\"Email\" class=\"form-control\"\u003e\n            \u003c/div\u003e\n            \u003cdiv class=\"form-group\"\u003e\n              \u003cinput type=\"password\" placeholder=\"Password\" class=\"form-control\"\u003e\n            \u003c/div\u003e\n            \u003cbutton type=\"submit\" class=\"btn btn-success\"\u003eSign in\u003c/button\u003e\n          \u003c/form\u003e\n        \u003c/div\u003e\u003c!--/.navbar-collapse --\u003e\n      \u003c/div\u003e\n    \u003c/nav\u003e\n\n  \u003capp-root\u003eLoading...\u003c/app-root\u003e \u003c!--this inserts the contents of app.component.html into this index.html page --\u003e\n\n\u003c!--footer section --\u003e\n    \u003cfooter\u003e\n          \u003cp\u003e\u0026copy; 2016 Company, Inc.\u003c/p\u003e\n    \u003c/footer\u003e\n\t\n  \u003cscript\n    src=\"https://code.jquery.com/jquery-3.1.1.min.js\"\n    integrity=\"sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=\"\n    crossorigin=\"anonymous\"\u003e\u003c/script\u003e\n  \u003c!-- Latest compiled and minified JavaScript --\u003e\n  \u003cscript src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\" integrity=\"sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa\" crossorigin=\"anonymous\"\u003e\u003c/script\u003e\n\n\u003c/body\u003e\n\n```\n\nThe 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. \n\n```\n\u003c!-- Main jumbotron for a primary marketing message or call to action --\u003e\n   \u003cdiv class=\"jumbotron\"\u003e\n     \u003cdiv class=\"container\"\u003e\n       \u003ch1\u003eHello, world!\u003c/h1\u003e\n       \u003cp\u003eWelcome to our first Angular2 blog. Please find our blog posts below.\u003c/p\u003e\n       \u003cp\u003e\u003ca class=\"btn btn-primary btn-lg\" href=\"#\" role=\"button\"\u003eLearn more \u0026raquo;\u003c/a\u003e\u003c/p\u003e\n     \u003c/div\u003e\n   \u003c/div\u003e\n\n\u003cdiv class=\"container\"\u003e\n  \u003capp-home\u003eLoading...\u003c/app-home\u003e \u003c!-- Notice that we are importing the contents of src/app/home/home.components.html here --\u003e\n     \u003chr\u003e\n\n   \u003c/div\u003e \u003c!-- /container --\u003e\n\n```\n\napp.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. \n* Notice that we are importing the contents of `src/app/home/home.components.html`. \n\nSo 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. \nSo open `src/app/home/home.components.html` and change the code there to: \n\n```\n\u003c!-- Example row of columns --\u003e\n\u003cdiv class=\"row\"\u003e\n  \u003cdiv class=\"col-md-4\"\u003e\n    \u003ch2\u003eHeading\u003c/h2\u003e\n    \u003cp\u003eDonec 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. \u003c/p\u003e\n    \u003cp\u003e\u003ca class=\"btn btn-default\" href=\"#\" role=\"button\"\u003eView details \u0026raquo;\u003c/a\u003e\u003c/p\u003e\n  \u003c/div\u003e\n  \u003cdiv class=\"col-md-4\"\u003e\n    \u003ch2\u003eHeading\u003c/h2\u003e\n    \u003cp\u003eDonec 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. \u003c/p\u003e\n    \u003cp\u003e\u003ca class=\"btn btn-default\" href=\"#\" role=\"button\"\u003eView details \u0026raquo;\u003c/a\u003e\u003c/p\u003e\n \u003c/div\u003e\n  \u003cdiv class=\"col-md-4\"\u003e\n    \u003ch2\u003eHeading\u003c/h2\u003e\n    \u003cp\u003eDonec 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.\u003c/p\u003e\n    \u003cp\u003e\u003ca class=\"btn btn-default\" href=\"#\" role=\"button\"\u003eView details \u0026raquo;\u003c/a\u003e\u003c/p\u003e\n  \u003c/div\u003e\n\u003c/div\u003e\n```\n\nThat settled, run `ng serve` and view your app on your browser by visiting `localhost:4200` . You should see a beautiful but static blog.  \nHere is what mine looks like:\n\n![image](https://cloud.githubusercontent.com/assets/1010556/20647101/8179b342-b48b-11e6-8fb9-601ebda37b5c.png)\n\n##Ng-Content Directive\nThis 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. \nNormally, if you had `\u003capp-home\u003eLoading... \u003c/app-home\u003e`. 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 `\u003cng-content\u003e \u003c/ng-content\u003e` at any part of the code you wish the contents of  `\u003capp-home\u003eLoading... \u003c/app-home\u003e` to be displayed. \nIts as simple as that - go to the component and tell it where to append the initial contents of its selector. \n\n\n##Routing and Navigation \nRouting 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.\n\nUpdate your  `src/app/app.module.ts` to the below, lookout for the comments I added.\n```\nimport { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { FormsModule } from '@angular/forms';\nimport { HttpModule } from '@angular/http';\nimport { AppComponent } from './app.component';\nimport { HomeComponent } from './home/home.component';\nimport { PostsAddComponent } from './posts-add/posts-add.component';\n\n//added\nimport { RouterModule, Routes } from '@angular/router'; \n\n//added: declare the route parameters below\nconst appRoutes: Routes = [\n  { path: 'posts-add', component: PostsAddComponent },\n  { path: 'posts-view/:id', component: PostsViewComponent },\n  { path: '', component: HomeComponent },\n  { path: '**', component: PageNotFoundComponent }\n];\n\n\n//added: RouterModule.forRoot(appRoutes) in the imports:[...] section below\n@NgModule({\n  declarations: [\n    AppComponent,\n    HomeComponent,\n    PostsAddComponent\n  ],\n  imports: [\n    BrowserModule,\n    FormsModule,\n    HttpModule,\n    RouterModule.forRoot(appRoutes)\n  ],\n  providers: [],\n  bootstrap: [AppComponent]\n})\nexport class AppModule { }\n\n```\n* `import { RouterModule, Routes } from '@angular/router';` - This imports the needed modules for the routing to take place. \n* `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.\n* `RouterModule.forRoot(appRoutes)` - This imports the defined parameters using the RouterModule imported in the beginning. \n* `{ 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.\n\nIf we wanted to send other parameters along with the url, you can use the `data` property. The route parameters will look something like this:\n\n```\n{\n    path: '/user/dave',\n    component: DaveComponent,\n    data: {\n      first_name: 'Dave',\n      middle_name: 'Partner',\n      networth: '$17b'\n    }\n  }\n  ```\n\n\nIf 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. \nSo go to your `src/app/app.components.html` and change `\u003capp-home\u003eLoading...\u003c/app-home\u003e` to `\u003crouter-outlet\u003e\u003c/router-outlet\u003e` .That all.\n\nHere is what my new  `src/app/app.components.html` looks like now:\n```\n\u003c!-- Main jumbotron for a primary marketing message or call to action --\u003e\n   \u003cdiv class=\"jumbotron\"\u003e\n     \u003cdiv class=\"container\"\u003e\n       \u003ch1\u003eHello, world!\u003c/h1\u003e\n       \u003cp\u003eWelcome to our first Angular2 blog. Please find our blog posts below.\u003c/p\u003e\n       \u003cp\u003e\u003ca class=\"btn btn-primary btn-lg\" href=\"#\" role=\"button\"\u003eLearn more \u0026raquo;\u003c/a\u003e\u003c/p\u003e\n     \u003c/div\u003e\n   \u003c/div\u003e\n\n\u003cdiv class=\"container\"\u003e\n  \u003crouter-outlet\u003e\u003c/router-outlet\u003e \u003c!-- added this --\u003e\n     \u003chr\u003e\n\n   \u003c/div\u003e \u003c!-- /container --\u003e\n\n```\nTo add a clickable link in Angular2, you just need to two angular2 attributes \n* `routerLink` - Angular2 does not make use of `href`, so `routerLink` is the attribute for specifying the address to be loaded.\n* `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`. \n\nLet's add some clickable links to the top navigation bar of this app. Go to `src/index.html`, scroll to the `\u003cbody\u003e`, locate the line that reads `\u003cdiv id=\"navbar\" class=\"navbar-collapse collapse\"\u003e` and add the following directly under it.\n\n```\n\u003cul class=\"nav navbar-nav\"\u003e\n\u003c!-- we have alread specified the respective routes in app.module.ts above --\u003e\n            \u003cli \u003e\u003ca  routerLink=\"\" routerLinkActive=\"activeLink\" \u003eHome\u003c/a\u003e\u003c/li\u003e \n            \u003cli\u003e\u003ca  routerLink=\"/posts-add\" routerLinkActive=\"activeLink\"\u003eNew Post\u003c/a\u003e\u003c/li\u003e\n\u003c/ul\u003e\n```\nNote that the above `routerLink` and `routerLinkActive` won't work if used in any file that is outside of inside of `src/app/` folder. This means it won't work in `src/index.html` file where we just used it above. We will need to copy the entire top navigation bar code out of `srcc/index.html` and paste it at the beginning of `src/app/app.coomponent.html` . \nMy `srcc/index.html` now looks like this:\n\n```\n\u003c!doctype html\u003e\n\u003chtml\u003e\n\u003chead\u003e\n  \u003cmeta charset=\"utf-8\"\u003e\n  \u003ctitle\u003eAngular2Blog\u003c/title\u003e\n  \u003cbase href=\"/\"\u003e\n\n  \u003cmeta name=\"viewport\" content=\"width=device-width, initial-scale=1\"\u003e\n  \u003clink rel=\"icon\" type=\"image/x-icon\" href=\"favicon.ico\"\u003e\n\n  \u003c!-- Latest compiled and minified CSS --\u003e\n  \u003clink rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\" integrity=\"sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u\" crossorigin=\"anonymous\"\u003e\n\n  \u003c!-- Optional theme --\u003e\n  \u003clink rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css\" integrity=\"sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp\" crossorigin=\"anonymous\"\u003e\n\n\u003c/head\u003e\n\u003cbody\u003e\n\u003c!-- navigation code was removed from here --\u003e\n\n  \u003capp-root\u003eLoading...\u003c/app-root\u003e \u003c!--this inserts the contents of app.component.html into this index.html page --\u003e\n\n  \u003cscript\n    src=\"https://code.jquery.com/jquery-3.1.1.min.js\"\n    integrity=\"sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=\"\n    crossorigin=\"anonymous\"\u003e\u003c/script\u003e\n  \u003c!-- Latest compiled and minified JavaScript --\u003e\n  \u003cscript src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\" integrity=\"sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa\" crossorigin=\"anonymous\"\u003e\u003c/script\u003e\n\n\u003c/body\u003e\n\u003c/html\u003e\n\n```\n\nMy `src/app/app.coomponent.html`now looks like this:\n\n```\n\u003c!-- added the below navigation  --\u003e\n\u003cnav class=\"navbar navbar-inverse navbar-fixed-top\"\u003e\n    \u003cdiv class=\"container\"\u003e\n      \u003cdiv class=\"navbar-header\"\u003e\n\n\u003ca class=\"navbar-brand\" href=\"#\"\u003e \u003ci class=\"glyphicon glyphicon-list-alt\"\u003e \u003c/i\u003e Angular2 Blog\u003c/a\u003e\n      \u003c/div\u003e\n      \u003cdiv id=\"navbar\" class=\"navbar-collapse collapse\"\u003e\n      \n      \u003c!-- Added the below two links with routerLink and routerLinkActive directives --\u003e\n        \u003cul class=\"nav navbar-nav\"\u003e\n          \u003cli \u003e\u003ca  routerLink=\"\" routerLinkActive=\"activeLink\" \u003eHome\u003c/a\u003e\u003c/li\u003e\n         \u003cli\u003e\u003ca   routerLink=\"posts-add\" routerLinkActive=\"activeLink\"\u003eNew Post\u003c/a\u003e\u003c/li\u003e\n        \u003c/ul\u003e\n\t\n        \u003cform class=\"navbar-form navbar-right\"\u003e\n          \u003cdiv class=\"form-group\"\u003e\n            \u003cinput type=\"text\" placeholder=\"Email\" class=\"form-control\"\u003e\n          \u003c/div\u003e\n          \u003cdiv class=\"form-group\"\u003e\n            \u003cinput type=\"password\" placeholder=\"Password\" class=\"form-control\"\u003e\n          \u003c/div\u003e\n          \u003cbutton type=\"submit\" class=\"btn btn-success\"\u003eSign in\u003c/button\u003e\n        \u003c/form\u003e\n      \u003c/div\u003e\u003c!--/.nav-collapse --\u003e\n    \u003c/div\u003e\n  \u003c/nav\u003e\n  \n\u003c!-- added the above ^^^  --\u003e\n  \n  \n\u003c!-- Main jumbotron for a primary marketing message or call to action --\u003e\n \u003cdiv class=\"jumbotron\"\u003e\n     \u003cdiv class=\"container\"\u003e\n       \u003ch1\u003eHello, world!\u003c/h1\u003e\n       \u003cp\u003eWelcome to our first Angular2 blog. Please find our blog posts below.\u003c/p\u003e\n       \u003cp\u003e\u003ca class=\"btn btn-primary btn-lg\" href=\"#\" role=\"button\"\u003eLearn more \u0026raquo;\u003c/a\u003e\u003c/p\u003e\n     \u003c/div\u003e\n   \u003c/div\u003e\n\n\u003cdiv class=\"container\"\u003e\n  \u003crouter-outlet\u003e\u003c/router-outlet\u003e \n     \u003chr\u003e\n\n   \u003c/div\u003e \u003c!-- /container --\u003e\n\n\n```\n\n\n## Custom Property Binding\nSo far, we have been passing data from the component class (`.ts` file) to and from the component view (`.html`) file. Now we are going to see how we can pass data from one component to another. There are two ways to do that - using the input or output decorator with a custom property binding.\n\n### @Input Decorator\nThe input decorator is used to pass data down from a compenent positioned at a higher level into a component at a lower level, like so :\n![image](https://cloud.githubusercontent.com/assets/1010556/20863397/3f7b8b76-b9c9-11e6-9dcc-e1af2f95aea4.png)\n\nThis can be useful in several scenarios one of which could be when you want to pass the list of menus from one component to the other. \n\nSo let us see how we can pass some sample data from `app.component` into `home.component`. It is done in 4 steps.\n* Declare the variables in `app.component.ts`. \neg. \n ```\n post = { \n        title : \"Welcome to Jamrock\", \n\tdescription : \"The quick brown fox jumps over a lazy dog\"\n       }    \t\n ```\n \n* Pass it as custom property in the selector for `home.component` located in `app.component.html` \nHere is an example\n ```\n \u003capp-home [myPost] = \"post\" \u003e \u003c/app-home\u003e\n```\n\n* Use the input decorator in `home.component.ts` to gain access to it.\n\n```\nimport { Component, OnInit, Input } from '@angular/core'; //add 'Input' to the list of imports\n.\n.\n.\nexport class HomeComponent implements OnInit {\n\t@Input() myPost; //use it here\n.\n.\n.\n```\n\n* Finally, you can make use of it in your `home.component.html` using string interpolation\nLike so:\n```\n\u003cp\u003e {{post.title }} \u003c/p\u003e\n\u003cp\u003e {{post.description }} \u003c/p\u003e\n```\n\n\n### @Output decorator\nThis does exactly what the @Input decorator does above but in the reverse direction. It enables data to be passed from a component in a lower hierarchical order (the sender) into a component that is higher in that order (the receiver). \n![image](https://cloud.githubusercontent.com/assets/1010556/20865248/5e09f462-ba0d-11e6-8066-67635a623914.png)\n\nIn this example we will pass data from `home.component` up to `app.component`. \nTo do that, we can start from the receiving component. We need to create a custom property, let's call it `onYell`, you can name it anything of course. After which we will attach it to a function that it will trigger.\n\nIn the `app.component.html` , modify the `home.component` selector to add our new custom property. \n\n```\n\u003capp-home (onYell)=\"yell($event)\"\u003e \u003c/app-home\u003e\n```\nThen we go to our `app.component.ts` and create the `yell()` function that will be triggered. \n\nIn `app.component.ts`, unnder (not inside) the constructor() method, add the following:\n\n```\nyell(receivedEvent){\n   alert(\"I just received a yell!); \n}\n```\nThe above function will fire when the custom event `(onYell)` is `emitted` from inside the `home.component.ts`.\n\nSo let's go to `home.component.ts` and output the event\n\n```\nimport { Component, OnInit, Input,Output, EventEmitter } from '@angular/core'; //import Output and EventEmitter\n.\n.\n.\nexport class HomeComponent implements OnInit {\n@Output() onYell = new EventEmitter(); //add this\n\n//The below function will be triggered from home.component.html when a certain button is clicked\nfireOnYellEvent(e){ \n   this.onYell.emit(e); \n   }\n.\n.\n.\n```\n\nFinally, go to `home.component.html` and add a button that will trigger the whole chain reaction.\n\n```\n\u003cbutton (click)=\"fireOnYellEvent($event)\"\u003e Click me! \u003c/button\u003e\n```\n\nAnd that's it. \nHere is what it looks like visually :\n\n![image](https://cloud.githubusercontent.com/assets/1010556/20865396/c20a23b2-ba10-11e6-95d9-3c39e02d5b7f.png)\n\n##Life Cycle\nThis session explains the lifecycle of an Angular App. Angular creates, updates and destroys directives and components as it runs there by giving them a life cycle. To tap into these key moments while our app is running we have to implement one or more of the Lifecycle Hook interfaces in the Angular core library as we will see below.\n\n### Bootstraping\nAngular 2 apps need to be bootstrapped, this is usually done in `src/app/app.module.ts` or in `src/app/app.component.ts`.\nThe `AppComponent` class was created and exported in  `src/app/app.component.ts` then bootstrapped in `app.module.ts` in the line that says `bootstrap: [AppComponent]` .\n\nThese are the two files you can put your application level code and configuration. Angular CLI automatically does most configurations for us in `src/app/app.module.ts`. This file basically contains configurations only. \nThe `src/app/app.component.ts`is just another regular component file sitting at the top as the root component, it's template is where the whole app component chain for your app gets created.\n\n### Lifecycle Hook interfaces\nWhen a component is created, its constructor is called. This is where we initialize state for our component, but if we rely on properties or data from child components, we need to wait for our child components to initialize first.\n\nTo run any particular component in your application, Angular first `creates` it, then runs its constructor() method. Every component has a constructor() method by default. The constructor is where we can initialise state for our component. The problem is that if that compnent relies on data and properties from child components, we will have to wait for those child components to initialize first.\n\nTo track that, we can make use of inbuilt Angular life cylcle hook interfaces. There are just a handful of them. Let's see a sample component with all the hooks.\n\n```\nimport { Component, OnInit } from '@angular/core';\n\n// Directive\n@Component({\n  selector: 'shopping-cart',\n  template: '\u003ccart-window\u003e\u003c/cart-window\u003e\u003ccart-controls\u003e\u003c/cart-controls\u003e',\n})\n\n// Component controller\nexport class ShoppingCart implements OnInit {\n\n\n  constructor(private logger: LoggerService) {\n  \t//here, write codes that will run soon as this component is loaded\n  }\n  \n  \n  ngOnInit() {\n    // here, write codes that will run soon as the child components are loaded\n    // In this case \u003ccart-window\u003e and \u003ccart-controls\u003e\n  }\n  \n  ngOnDestroy() {\n    // write code that runs when component is destroyed\n  }\n  \n  ngDoCheck() {\n    // Custom change detection\n  }\n  ngOnChanges(changes) {\n    // Called right after the bindings have been checked but only\n    // if one of the bindings has changed.\n    \n  }\n  ngAfterContentInit() {\n    // write code that runs when component content has been initialized\n  }\n  ngAfterContentChecked() {\n    // write code that runs when component content has been Checked\n  }\n  ngAfterViewInit() {\n    // write code that runs when component views are initialized\n  }\n  ngAfterViewChecked() {\n    // write code that runs when component views have been checked\n  }\n}\n\n```\n\n##Pipes\nAngular pipes take data as input then transform them to the desired and more user friendly output. To put it in simple terms, Angular pipes are basically string manipulation. It is used in the view to determine how the user eventually sees a piece text/data.\nFor instance, you may wish to transform the casing of the username you received from the database from something like `dave partner`, to `Dave Partner`. \nPipes can be used to shorten texts, transform dates, search/filter a list and so on. Angular has some standard inbuilt pipes, but you can create yours if you want. We'll give an example or two here. You can read the rest on [Angular's official documentation](https://angular.io/docs/ts/latest/guide/pipes.html)\n\nLet us assume that we have a variable set in our controller like so:\n```\nimport { Component } from '@angular/core';\n\n@Component({\n  selector: 'hero-birthday',\n  template: `\u003cp\u003eThe hero's birthday is {{ birthday | date }}\u003c/p\u003e`\n})\nexport class HeroBirthdayComponent {\n  fullName = \"Dave Partner\";\n}\n```\n\nIn our view we can transformm the value of `firstName` to upper case by using a pipe ` | ` like so:\nFirst of all, let us display it without any pipes:\n```\n\u003cdiv\u003e {{fullName}} \u003c/div\u003e\n```\nThe output would be `Dave Partner`.\n\n```\n\u003cdiv\u003e {{fullName | uppercase}} \u003c/div\u003e\n```\nThe output would be `DAVE PARTNER`.\n\nWe can also slice the first letter of the `firstName` off like so:\n```\n\u003cdiv\u003e {{fullName | slice : 1}} \u003c/div\u003e\n```\nThe output would be `ave Partner`.\n\nLet us slice the first letter, then go forward and slice off whatever is left after the 4th letter:\n\n```\n\u003cdiv\u003e {{fullName | slice : 1 : 4}} \u003c/div\u003e\n\n```\n\nThe output would be `ave P`.\nWe can chain multiple pipes together  too by just including ` | ` before each new pipe:\n\n```\n\u003cdiv\u003e {{fullName | slice : 1 : 4 | uppercase }} \u003c/div\u003e\n```\n\nThat's it, pipes are really very easy to use, you can discover more pipes on Angular's official documentation.\n\n\n##Services \nServices help you avoid repeating your self. Generally, any chunk of code you need to use in more than one component should be a service.  Several components can connect to one service. One component can connect to many services. Below is a before and after picture to demonstrate the importance of services. \n\nWithout services, you'll have to write all your code inside your component.  If you need the same code in another component, you'll have to rewrite it.\n\n![image](https://cloud.githubusercontent.com/assets/1010556/21512514/ae160a96-ccae-11e6-85fa-e55346026075.png)\n\nWith services, you just need to write it once as a service and deploy to several components.\n\n![image](https://cloud.githubusercontent.com/assets/1010556/21512600/928f0f92-ccaf-11e6-9198-6146e12dfc78.png)\n\nTo create a service, run `ng g s \u003cname of service\u003e`. For instance to create `posts.service.ts`, run `ng g s posts`. This will generate a a file named `posts.service.ts` in `src\\app\\`.\n![image](https://cloud.githubusercontent.com/assets/1010556/21580707/e36f32ce-d00c-11e6-82e4-5c299651226e.png)\n\n You will see a screen if yours was successful, otherwise restart your command prompt, navigatte to your project folder and run again.\n\n![image](https://cloud.githubusercontent.com/assets/1010556/21580704/8875f6a0-d00c-11e6-9e85-d088aeb8dadf.png)\n\n\nSometimes, Services are like your models in MVC, for those coming from MVC background. As best practice one model should handle everything relating to one table in your database. Sometimes services have nothing to do with any database, they could just be a house for reusable codes.\nFor instance, the posts service should handle everything that has to do with creating, deleting, modifying and listing posts. Therefore we should create such methods.\n\nFor example purposes, we will be writing a simple code that says \"hello world!\" in our `posts.service.ts` . Then we will access that block of code from 2 other components namely `posts-add.component.ts` and `home.component.ts`. These are two components we created in the past.\n\nSo, open the new service you created, its located in `src\\app\\posts.service.ts`. Then add a new method outside the constructor function. The new method we will add will just pop an alert box saying \"hello world\". The method can be named anything. Below is a sample:\n\n```\n\tshowAnAlertExample(){\n\t\talert(\"Hello World\");\n\t}\n```\n\nMy `src\\app\\posts.service.ts` now looks like this, after I added the method above. I have added comments where necessary. \n\n```\n\timport { Injectable } from '@angular/core';\n\n\t@Injectable()\n\t//notice that the exported class here is named 'PostsService' That's what we will need when importing it into any component.\n\t\n\texport class PostsService {  \n\n\t  constructor() { }\n\n\n\t//I added the below method\n\t  showAnAlertExample(){\n\t   alert(\"Hello World\");\n\t }\n\n\n\t}\n\n\n```\n\nNow that is sorted, the next thing to do is to import this service into any component where we will need it. Let's import it into `app\\posts-add\\posts-add.component.ts`. Open the file and write the following import statement at the top of the page. \n\n```\nimport {PostsService} from '../posts.service.ts';\nimport { Component, OnInit } from '@angular/core';\nimport {PostsService} from '../posts.service.ts';\n@Component({\n  selector: 'app-posts-add',\n  templateUrl: './posts-add.component.html',\n  styleUrls: ['./posts-add.component.css']\n  providers : [PostService] \n})\n\nexport class PostsAddComponent implements OnInit {\n\n  postTitle = \"The quick brown fox \"; //added this\n  postDescription = \"Jumps over lorem Ipsum fox mesit\"; //added this\n\n  constructor(public ourPostsService : PostsService) {\n\n  //all codes in this constructor() block executes automatically whenever this component is called.\n  \tthis.ourPostsService.showAnAlertExample();\n  }\n\n  ngOnInit() {\n  }\n\n  addNewPost(){\n    //method to exectute when the submit button is clicked\n  }\n\n}\n\n```\n\nThen name `PostsService` as a provider in the `@Component` section of the page.\n\n```\n@Component({\n  selector: 'app-posts-add',\n  templateUrl: './posts-add.component.html',\n  styleUrls: ['./posts-add.component.css']\n  providers : [PostService] //I added this line, but you dont have to add this comment to avoid errors.\n})\n\n```\n\nAfter this, you have to name it as a parameter in the `Constructor()` . You can use any variable to declare it but it must be of the type `PostsService`. I will use the variable `ourPostsService`. \n\nThe constructor now becomes :\n\n```\n  constructor(public ourPostsService : PostsService) { }\n```\n\nFinally, you have to actually call the function. So far what we have done is to propery connect our `posts.service.ts` to the component `post-add.component.ts`. \nRemember that the function in the service we want to call is named `showAnAlertExample()`. For example purposes, We can call it directly from inside our constructor() method so that once the page loads, the alert will show. \nOr we can create a new method for it outside of the `constructor()` method in `posts-add.component.ts` so that we can trigger it with a button on the view side `posts.add.component.html` .\n\nLet's take the first option just to demonstrate the point. \n\nUpdate the constructor() method of  `posts-add.component.ts` to contain a call to the service.\n\n```\nconstructor(public ourPostsService : PostsService) {\n\n//all codes in this constructor() block executes automatically whenever this component is called. \n\tthis.ourPostsService.showAnAlertExample();\n}\n```\n\nDone, run : ng serve, navigate to your posts-add component and you will see the pop up. This process is identical for any other component you wish to use the service in. Just import it, name it as a provider, declare it as a parameter in the constructor and then start making calls to it from anywhere in that component.\n\nMy complete  `posts-add.component.ts` now looks like this:\n\n```\nimport { Component, OnInit } from '@angular/core';\nimport {PostsService} from '../posts.service.ts';\n@Component({\n  selector: 'app-posts-add',\n  templateUrl: './posts-add.component.html',\n  styleUrls: ['./posts-add.component.css']\n  providers : [PostService] \n})\n\nexport class PostsAddComponent implements OnInit {\n\n  postTitle = \"The quick brown fox \"; //added this\n  postDescription = \"Jumps over lorem Ipsum fox mesit\"; //added this\n\n  constructor(public ourPostsService : PostsService) {\n\n  //all codes in this constructor() block executes automatically whenever this component is called.\n  \tthis.ourPostsService.showAnAlertExample();\n  }\n\n  ngOnInit() {\n  }\n\n  addNewPost(){\n    //method to exectute when the submit button is clicked\n  }\n\n}\n\n\n```\n\n\n## HTTP Service\nHTTP is the primary protocol for browser/server communication. It helps your app to talk to a remote server. This could be a json file seating right in your project or some remote server like firebase or your website. \n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdavepartner%2Fangular2-tutorial-with-firebase-book","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdavepartner%2Fangular2-tutorial-with-firebase-book","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdavepartner%2Fangular2-tutorial-with-firebase-book/lists"}