Starting with Angular 4

This is one of the ways how you would create a new project and start with Angular 4. There is another way to start a new Angular 4 application using a command line tool – Angular CLI. I will discuss the differences between the two approaches and the benefits of using Angular CLI at the end.

#1 Quickstart with Angular 4

I have basically followed the Angular tutorial here, but I will try to make it even simpler for you to understand, especially if you haven’t coded in TypeScript before, like me.

TypeScript is a typed superset of JavaScript that compiles into plain JavaScript. So what you actually do is start writing JavaScript the object-oriented way, using TypeScript. You will create something called as classes, make them exportable and reusable, import them in other parts of your application as required. You will also do some inheritance, create constructors in your classes, and also give a data type to every variable that you create and use. You can start with TypeScript also first if you want from here before you go ahead with Angular.

If you have only written like JavaScript and never explored any type-strict languages like Java before, you better get some concepts about Object Oriented Programming cleared from before moving on, because those will help. I have worked in Java before so it was easier to build up understanding while writing TypeScript.

Setting up before you can start doing anything

I use Ubuntu 14.04 as my current operating system. I am assuming you are working with Ubuntu, or a similar OS, so you will need:

  1. A terminal
  2. A code editor of your choice (Atom + this TypeScript plugin  – that is what I use.)
  3. A browser to view what you have coded (Firefox or Chrome is good)

Open your terminal and install Node and npm if you don’t have them already. Make sure Node is v4.x.x or higher and npm is v3.x.x or higher. Follow this link to install Node and npm.

Once done, create a project folder (name it anything you like) and run the following commands in your terminal

git clone https://github.com/angular/quickstart.git projectfolder
cd projectfolder
npm install
npm start

That should start the server to serve the current project and you can open your browser to view http://localhost:3000/. To close the server, use Ctrl + C .

Now, lets delete a few files that we don’t need and reduce the distraction. Run the following commands:

xargs rm -rf < non-essential-files.osx.txt
rm src/app/*.spec*.ts
rm non-essential-files.osx.txt

Now these are the main files that we will focus on:

src/
---- app/
-------- app.component.html
-------- app.component.ts
-------- app.module.ts
---- main.ts
---- index.html
---- (... some other files)

Remember, that now we will only be writing TypeScript and no *.js files. So before we get into each of the individual files, let me walk you through how Angular 4 will work. The app will start with the index.html file, this file will have the default html, head and body tags and will link external style sheets and script files. It will also have a root element such as <app-root></app-root> in this case. You can name this element anything. The same will have to be mentioned in the file app.component.ts.

Before that, lets look at app.module.ts , that is important. This file describes the root module, the one which is like a directory where all the other modules and components have to be registered.

To make sense of everything, Angular is a tree of modules with one root module called the NgModule, which tells Angular how to compile and run your application.

This is what the app.module.ts file looks like at the moment:

//app.module.ts
import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent }  from './app.component';

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

I’ll explain each of the lines one by one. First three statement are import statements, each importing a module or a component. The NgModule is imported from the ‘@angular/core’ file, which tells us that we are describing the root module in this file. The description is written using @NgModule() decorator, by usually passing three different arrays to it, an imports array where we supply names of all the other Modules that our app requires, a declarations array where we supply names of all the Components that our app is made up of, the last array, bootstrap is where we supply the Component that is to be used for bootstrapping and inserting the component into the DOM. Most applications have only one component tree and they bootstrap a single root component. You can call the one root component anything you want but most developers call it AppComponent.

Next is the BrowserModule. Many features of Angular itself are organized as Angular modules. HTTP services are in the HttpModule. The router is in the RouterModule. So for our application to work in a browser we have some features we require from the BrowserModule.

Finally we are importing the AppComponent here. We will look at the contents of that file, but before that the last line in the app.module.ts file – almost every file that we will write, will have a class declaration that is exportable. So AppModule is that class name, preceded by the export keyword making it available to be used.

In the main.ts file, we write about how we want to compile the application and where we want to run it.  In the beginning, we will compile the application dynamically with the Just-in-Time (JIT) compiler and run it in a browser. We can learn about other options later. So this is the basic content of the file.

//main.ts
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule }              from './app/app.module';

platformBrowserDynamic().bootstrapModule(AppModule);

So that AppModule is imported into the main.ts file and given for bootstrapping and running in the browser. Now lets look at the final important file – app.component.ts.

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

@Component({
  selector: 'my-app',
  template: `<h1>Hello {{name}}</h1>`
})
export class AppComponent { name = 'Angular'; }

This file, will now be much easier to look at and tell what’s happening. The first import statement tells us that we are creating a new Component, declaring it using @Component() decorator and making it available to others via the last line where we declare the exportable AppComponent class. In the @Component() decorator, we mention the selector, the element that we created in the index.html file. We also supply the template (the HTML) that is to be loaded in that selected DOM element. We can write the template here itself if it is a short one, else we can create a separate HTML file and then supply it here in place of the template. So if we create a new file app.component.html in the src/app folder, the template line will be replaced with:

  templateUrl: './app.component.html'

Also notice that we were using ` (back ticks) when declaring the template and using the ‘ (single quote) when giving the path to the template HTML file.

Now, this point onwards, just follow the angular tutorial itself, starting this point. The documentation will now make sense.

Read it through and through, write and execute the code. Don’t copy paste.

That way you will be aware of what changes you have made and understand how everything is working. Keep transpiling and running your application, and open in the browser, it will automatically reload every time you make and save changes to your files.

You can also have a look at this repository that I was working with when following the Angular tutorial.

#2 Using Angular CLI to start new Angular project

The Angular CLI is a command line interface tool that can create a project, add files, and perform a variety of ongoing development tasks such as testing, bundling, and deployment.

So if it isn’t clear from the above line, a lot of things get easier, faster if you are using Angular CLI.

  • You get testing added to you project by default when you initialize and create the application – both Unit Testing (using Karma) as well as End-to-end testing (using Protractor).
  • Creating new files for adding components, directives or anything else to your project becomes as easy as running a command from your terminal, because that’s exactly what you do.
  • Your app is git initialized by default, the .gitignore file is already setup correctly to ignore all the extra files that you might never edit and work with, but will be required for your application to run.
  • You won’t have to npm start, you will only have to ng serve.

You can setup Angular CLI using just one command, if you already have Node and NPM installed. (Node v6.9.x and above; NPM v3.x.x and above)

npm install -g @angular/cli

After this, all of your work can be done using the ng command.

To create a new app

ng new my-app

Serve and see the app alive.

cd my-app
ng serve --open

The --open option opens the browser, you may skip it if your browser is already open and just navigate yourself to http://localhost:4200/.

To generate any new class, component or one of the other 7 things,

ng generate [name]

And to run any of the tests

ng test
ng e2e

According to me, you should be aware of both the ways of starting an Angular application, but if you have the choice, do think about using the CLI way to do it. Everything comes with a learning curve, but look at the advantages of each method! 🙂

Leave a comment if you have any questions, I will surely try and answer them! Also if you want to suggest any topic that you want me to cover, do let me know, I’ll be glad to do it! 🙂

Advertisements

What do you have to say? Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s