ITBusinessHub
angular itbusinesshub

Angular tutorial notes – The basics

Angular is one of the hottest front-end development framework for creating Single Page Applications or SPA. Angular is maintained by Google and has been recently re-written from ground up to make it more modern and performance focused. If you are unfamiliar with AngularJS (The older version of Angular), it should be perfectly fine to get started with this tutorial notes. This article is more of a quick summary of what you would learn to begin coding Angular projects. This tutorial notes expects the reader to be well versed with a bit of HTML, CSS and JavaScript concepts.

For those, who are new to some basic concepts, I’ll take some time to explain them on wards. Please feel free to skip sections below based on your comfort level.

Index

Summary of coverage of this tutorial

Let’s run through a quick summary of our approach towards this tutorial. For the purpose of this article, we’ll stick to the method of using Angular CLI to get started with Angular. The other un-advocated method of beginning with development of an Angular app would be to create all the basic files from scratch or by cloning the repo. Angular- CLI is a great tool and will help us create lots of required files on the go.

After understanding few required tools, we’ll begin understanding the basic fundamentals of Angular.

These would be Components, Templates, Routing & Navigations, Services, and Bindings . We’ll use Angular CLI to generate these files, but will also have a look at the manual way- so that the basic architecture is well understood.

Before that, for the absolute beginners amongst us- let’s look at few basic concepts like Single Page Application and the tools we need.

What is a Single Page Application.

Single Page Application, is an approach to design your websites with nothing but just a single page . As the name suggests, your entire website is a single page and dynamically hides and shows contents on the same page. The URL in the address bar can be virtually changed as well- to give the end user an virtual view of change of pages. The data within the different views can be populated by using APIs that talks to the backend systems.

Single Page Applications approach is mostly useful, when one is designing a web app- where the contents within the page simulates an app. However, since in most cases the whole code loads on the first hit to your servers, the initial load of your website might be slower.

Now that we know the concept of Single Page Applications or SPA, lets kickstart our Angular Journey.

What is Node Package Manager or NPM

To define it- Node Package manager is a software that helps you manage and pull pre written packages from the repository. We’ll have npm or node package manager installed on our systems when we install Node.JS. With NPM, you can then pull pre written packages from the repository.

Rewriting code and re inventing the wheel is something that a smart developer should avoid. Lot’s of alike developers share their code on the repository and you can make use of them.

In order to pull Angular-CLI ( A tool we will use to generate angular files for our app. More on this later) from the repo, we will need npm or Node Package manager.

Begin with installing Node JS . Download the latest LTS version of Node JS from here. LTS or Long term Support versions should be stable enough for our development purposes.

Once you have installed Node JS Successfully, you can check the latest version of node by using the below command on your terminal or command prompt.

    node -v

What is Angular CLI ?

Angular CLI is a command line interface for Angular.

With Angular CLI you can quickly generate an Angular project, generate various files for components, routes, services, pipes etc. Angular CLI cuts down on the various repetitive tedious tasks you might have to do to build and deploy an Angular App.

How to install Angular-CLI

(Angular CLI)[https://cli.angular.io/] can be installed with the below command on your terminal or command prompt once you have successfully installed Node JS

npm install –g @angular/cli

The –g flag tells npm to install the module globally. This means you need not install angular cli every time you need to use it for developing a different app.

That’s all you need to do to install Angular CLI

You can now check the version of the angular cli by typing the below in the console.

ng –v

Starting a fresh new angular project with angular CLI

With Angular-CLI, one can start a new angular project in a jiffy. Head down to your specific folder on the terminal, where you need to start the new project. Create a new project with the following command.

ng new project-name

Believe it or not, your Angular project is now created- with all the necessary files, components and modules, thanks to CLI. You can now in fact serve or view this app in the browser. We have an inbuilt server and can use that to serve the app.

Change directory to the root of the new app you just created.

Assuming you named your project as project-name

cd project-name    

And then hit the below commands to serve your app.

ng serve

This spins up the server and serves your app at the mentioned port (usually 4200).
Visit your site on the browser at http://localhost:4200

Changing the default port of Angular CLI served site

If you are running multiple sites using CLI or just need to spin up another site on a different port, you can dictate the CLI to serve the site on a different port. Below is the command:

ng serve --port portnumber

e.g., If 4201 is the port you are looking to serve your site, the command would be

ng serve --port 4201

On the other hand, you can also specify the port number in your angular.json file

"projects": {
    "your-project": {
        ... 
        "architect": {
            "serve": {
                "options": {
                    "port": YOURPORTNUMBERHERE
                }
            }
        }
    }
}

What are Components in Angular

For a beginner, component can be described as the building block of your angular app. A component can include the logic, view and styling of the basic building block. Components can be used and reused throughout your app.

Components can also receive inputs and provide outputs thus talking to other components in your app.

For e.g., If you are building a To-do app list, it contains many to-dos in the list. You can build a component for a single To-do entry in the list and use and reuse it to dynamically build the long list.

Understanding the basic structure of Component in Angular

Let’s look at a sample code for an Angular component.

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

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

export class AppComponent {
title = 'app works!';
}

A component in Angular consists of three main sections:
– The imports
– The component decorator which defines the meta data associated with it
– The exported Class that contains the properties and methods (Can also be referred to as variables and functions if you an early beginner to programming)

Let’s analyse each of these sections of an Angular Component

The import section:

The import section allows us to import other exported components, members from angular library, third party libraries and modules etc. The bare necessary import in the Angular component would be the basic definition of Component from the angular core library.

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

The component decorator section:

The component decorator describes all the necessary meta data related to the component. It is known as a decorator since it begins with the @ symbol.

The metadata of the component includes the below and is defined as a parameter inside curly braces.

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

selector: defines the html selector which the angular app will use to inject the component logic and details.

templateUrl: defines the file where the template of this particular component is defined. Alternatively, you can also specify the template within the component by using the ‘template’ keyword instead of ‘templateUrl’. It is recommended to keep the template within the same component, if the structure is quite short. For better organization purposes, it is better to have a separate file for template, if it is quite large.

styleUrls: This is an array of files referring to the stylesheets of this particular component. Alternatively, you can also use the ‘styles’ keyword to specify the styles within the component decorator.

The exported class section of component:

This section is the Class definition of the component and includes the properties and methods. Properties are the variables you define and methods refers to the functions within this class which can be optionally accessed from outside.

export class AppComponent {
title = 'app works!';
}

The Class is the meaty logic section of your component.

For e.g., If you were to write a component for a list in the to do list, the Class would include the function to write data to the variable etc.

The export class defines the class name (AppComponent in above example) which can then be referred to by other components for imports.

How to generate components

Angular Components can be generated using the Angular CLI tool or manually as well.

However there are few steps to do- if you go the manual route. We’ll learn both the angular and manual way, as knowing these helps us better understand the structure and debug any issues.

Manually generating angular components:

In order to manually generate a angular component, you’ll have to first create the component file. Place this file in the folder you wish as per your organizing needs. Component files are always named with “.component.ts” as the file name and extension (Assuming we are using Typescript )

For e.g., name your file ‘first.component.ts”

Now, In order for Angular to know the existence of this component, we need to do two things.

  • Import the component in the module referring to the file with it’s path
  • Then declare this import in the declarations array.

Open app.module.ts file and begin with importing the component

(This tells Angular of the file and the component)

Then declare this in the declarations array

(This tells Angular that we are using this imported component )

Generating angular components using Angular CLI:

Generating components with Angular CLI is rather very straightforward as this tool does the job of importing and declaring it in the app.module.ts

The command to generate angular components using angular cli is:

ng generate component componentname

This tells cli to generate a component with the specified component name.

The below shortcut command can also be used to generate components

 ng g c componentname

g refers to generate
c refers to component

Creating components in specific folders using angular cli is rather simple too. You specify the path of folders and then the component name

E.g., Creating a first component inside common/product folder would be like

ng generate component common/product/first

OR the below for shortcut angular cli command

ng g c common/product/first 

Styling your angular app with frameworks

If you would prefer to use bootstrap or foundation or any other styling framework for that matter in your angular projects, you could import in your project.

Let’s have a look at the possible options and ways to do it, using Twitter bootstrap as an example.

Including Bootstrap CDN in index.html

The quick and easy way to include Bootstrap CDN in your app would be to include the CDN link in your index.html file

Head over to index.html and include the style as below.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

Hosting Bootstrap inside your app

Alternatively, you could host the Bootstrap files with your app and refer to it. To install the boostrap files using npm, begin with the below commands

npm install bootstrap@next --save

This tells npm to look for bootstrap in the repo and install it within this app.

Once installed – you need to include the path to the CSS and the scripts in the angular-cli.json file which you’ll find in the project’s root folder.

"styles": [
"../node_modules/bootstrap/dist/css/bootstrap.css",
"styles.scss"
],
"scripts": [
"../node_modules/jquery/dist/jquery.js",
"../node_modules/tether/dist/js/tether.js",
"../node_modules/bootstrap/dist/js/bootstrap.js"
],

Routing in Angular App

If you opted for installing routing module, while generating a new app using the angular-cli, the necessary routing modules are created for you. If not, you can manually create these files and import- declare them in the app module.

Routing helps manage the angular app to display different components and contents based on the different URLs entered by the user.

There are four basic steps to get routing done in Angular
– Define all the files and imports in the app modules
– Define all the constant routes
– Define router-outlet – where your router will display its contents
– Change your navigation links (if any) to suite the router

Let’s have a look at the routing files.

Note: If you did not use angular-cli, then you can optionally create these files as we discuss them.

Heading over to the app folder inside source, look for (or create) app-routing.module.ts file

This file includes the necessary imports to define a module and routings. Followed by the imports is the constant Routes, where we’ll define all our routes. Finally we’ll export this Module for it to be imported in app.mdoule.ts

app-routing-module.ts

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

const routes: Routes = [];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }

Inside the app.module, import the routing module

import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';

And declare it in the imports array as such.

imports: [

AppRoutingModule
],

The constant Routes in the app routing module file, is where we will declare all our routes. In order to declare routes, one has to define the path and the component.

For e.g.,
Say we had an about component and want the user to see these contents when user visits the path /about or see the contents of the contact component when user hits the URL /contact

The entry in the Routes array would be as such:

export const router: Routes = [
    { path: 'about', component: AboutComponent },
    { path: 'contact', component: ContactComponent }
];

Usually, one can also define the blank path which refers to the home page and use redirectTo as another parameter to route the component.

E.g., an entry referring to home page in the routes constant.

export const router: Routes = [
    { path: '', redirectTo: 'about', pathMatch: 'full' },
    { path: 'about', component: AboutComponent },
    { path: 'contact', component: ContactComponent }
];

Adding router-outlet:

The router outlet is the selector where your router will display its components in.

So if you add the router-outlet to the main app component, based on the url visited- the contents within this app component will change.

<router-outlet></router-outlet>

Changing your navigation links to suite the router

If you would have any navigation links- the a href’s need to define the routerLink with the path of the component.

For e.g.,

<ul>
<li><a routerLink="about">About</a></li>
<li><a routerLink="contact">Contact</a></li>
</ul>

Ensure the base href tag is in index.html

<base href="/">

The base href tag in index.html isn’t something specific to Angular. It is an HTML tag which is used to specify the root of the resources, which includes but not limited to script inclusions, media files and style sheet locations.

What are services in Angular

Services in Angular are nothing but JavaScript functions with its properties and methods that can be used by various components. If you need some specific tasks that need to be done, you could write a service for it and call it in every associated component.

For e.g., you could write a service that helps fetch data from the internet with the specified URL/ API. This service can then be injected in every component which needs the functionality of calling some internet or API URL to pull data.

How to create a service in Angular

Services can be created using the Angular-CLI way or without. Let’s learn the both the CLI and non CLI way or manual way, as it teaches us the basic necessary steps to build a service and can help us debug if we hit any errors.

Creating an angular service manually

Begin with creating the service file in your desired folder inside the app.

Service files end with filename and extension as “service.ts” (again, assuming you are using TypeScript).

So if your service is called the getdata service, you could name the file getdata.service.ts

The service file follows somewhat similar structure as components, but with different imports and decorator. A service has the same stuffs in the file- Necessary imports, Injectable decorator declaration and the Class with necessary methods or functions.

Imports: The service files needs a Injectable import from the angular core .

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

Injectable decorator: As similar to component decorator in Component files, we need to declare the @Injectable() decorator in services.

    @Injectable()

The Service Class: Again, similar to the Class exports on the Component class, we need a similar class export for Services. This Class will include the functions and properties.

export class GetdataService {
// Declare your functions and variables here. 
    yourfunction() {
            return 'Hello!';
        }
}

All your components and services file names needs to follow the appropriate case for class name.

For e.g., if your filename reads getdata.service.ts- > The corresponding Class name is GetdataService

Creating a service using the angular cli :

With Angular CLI the command to generate the service is quite simple.

ng  generate service servicename

OR the shortcut way

ng g s servicename  

Where ‘servicename’ is the name of the service.

This generates the appropriate service file with the imports, decorator and the class name.

You’ll have to include the service in the NgModule decorator of app.module.ts – if all your components need to use this service. You can include the service in the specific component file too. Read below on how to use the service for more details.

Using a service in your Angular Components

In order to start using the service in your component, you first need to import it in your component’s imports.

E.g.,

import { Component } from '@angular/core';
import { GetdataService} from './getdata.service';

Next, you begin with providing the import inside the Component decorator. (This is optional if you provide it inside the app module which is accessible by all Components)

E.g.,

@Component({
    selector: 'my-app',
    template: '<h1>{{ title }}</h1>',
    providers: [GetdataService]
})

The provided service then can be dependency injected in the constructor of your component class.

constructor(private _st: GetdataService) {
}

The service’s methods or functions can then be called in various methods of your component.

E.g.,

ngOnInit(){
     this.value=this._st.getAPIValue();
     }

Where getAPIValue is a method of the service class.

Property and Event Binding in Angular.

In most modern apps, your variables might have to talk to the values in the elements on the view. Also the other way around, button clicks on entries in some input fields needs to be sent to variables in Classes. As such we have to bind these together so that they communicate with each other.

If you were familiar with Angular JS (The older implementation of Angular), we had something called as digest cycle.

Digest cycle used to make sure your view and logic was always in sync. This was called as two way binding- as such any change on either side would notify the other cousin. However, two way binding is taxing on performance. With Angular, we are done with default two way binding. (You may implement if you need one, however the default two way binding is absent for good.)

Let’s have a look at property and event binding in Angular and see ways to implement one way or two way binding.

Property Binding in Angular

As the name suggests, property binding – you bind the property of the elements in the view to the variables in your classes.

For e.g., you want to dynamically bind the source (src) property of an image element in your view with a value in your class.

The template or view would go this way:

<img [src]="urlValue">
<img bind-src="urlValue">

And the function or association of this variable in your class would be something like below.

export class AppComponent { 

urlValue = 'https://lh3.googleusercontent.com/8J_qLN4Coyzuf4u-Z5K_d1iPXBDk1rE_LG6VaN3GUBPMgAgfPr_82xpawC1XpabtbGvDXIJ4TSv8_8mu50GprRIKPocp3WzPgUFmutps';

}

In order to property bind your elements, you either use the square brackets [] or the keyword bind-property , like bind-src or use the {{ }} (double curly brackets) as in older version of angular.

The value then can be tweaked in your classes or functions.

Event Binding in Angular

Event binding, as the name suggests binds events from the view to the functions in your classes. Thus Event bindings are usually from view to your logic in classes.

For e.g., If you want to event bind a button to execute a function from your class, the code would go as below.

In your template:

<button (click)='myFunc()'>
<button on-click='myFunc()'>

and the function or method would be in your class as such :

myFunc() {
console.log('Helluyah ! Bazinga !');
}

Event binding can be used by wrapping the event using round brackets ( ) or using the keyword on- followed by the event.

Needless to say, you can pass event paramters to your function in the class as well.

e.g.,

<button (click)='myFunc($event)'>
<button on-click='myFunc($event)'>

myFunc(e:any) {
console.log('Helluyah ! Bazinga !' + e.value);
}

Two way binding in Angular

Now, in certain cases you might want to bind variable in the view that talk both ways. That is, any changes from the view will change the value of the variable in your class, or any changes from the class will render on the view.

This can be achieved by using both the square and round brackets wrapped around the model- [()].

Remembering, “Banana in a box” , will help you recall the order of the brackets. The round brackets always goes inside the square brackets.

Using ngModel directive, we can easily achieve this linking.

Let’s look at an example of two way binding in Angular.

<input [(ngModel)]="username">
<p>Hello {{username}}!</p>

Here, any entry to the input field will sync with the view and render it besides “Hello”. On the other hand, if you manipulate the value in username using your components or say API for that matter, it would render it in the view and input field.

Another example for two way binding using a custom directive would be as below:

<custom-element [(customvalue)]="someValue"></custom-element>
<p>{{someValue}}</p>

So, that’s all folks. The above was a quick summary notes on the basics on Angular app. Now that we know some of these concepts, you can start with a new app using the cli and start tweaking it to build and use components and services.

Best luck !

Suhas T

Add comment