Angular : How to make REST API Calls ?

In this tutorial we will learn about Angular REST API Calls.

Note : Module to be used for REST API Call

import { HttpClientModule } from '@angular/common/http';

In src/app/app.module.ts file import HttpClientModule and add it to the imports array:

...
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    // [...]
    HttpClientModule,
  ],
  // [...]
})
export class AppModule { }

SERVICE class : to write all the CRUD API requests

import {Injectable} from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
 
const httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
 
@Injectable()
export class ApiService {
 
    constructor(private http:HttpClient) {}
}

GET API Request in Angular

Now adding a get method in ApiService for the GET API request.

    // Uses http.get() to load data from a single API endpoint
    getEmployees() {
        return this.http.get('/api/employees');
    }

Our ApiService makes the HTTP request and returns an Observable object. To actually get the data from the service, we need to update our component to subscribe to the Observable. Lets check below.

app.component.ts

ngOnInit() {
    this.getEmployees();
  }
 
  getEmployees() {
   this._apiService.getEmployees().subscribe(
      data => { this.employees = employees },
      err => console.error(err),
      () => console.log('done loading employees')
    );
  }
}

The subscribe() method takes three arguments which are event handlers. They are called onNext, onError, and onCompleted.

The onNext method will receive the HTTP response data. Observables support streams of data and can call this event handler multiple times. In the case of the HTTP request, however, the Observable will usually emit the whole data set in one call.

The onError event handler is called if the HTTP request returns an error code such as a 404.

The onCompleted event handler executes after the Observable has finished returning all its data. This is less useful in the case of the Http.get() call, because all the data we need is passed into the onNext handler.

Other HTTP Request : PUT, Delete, POST http requests

Now we will write other HTTP methods like PUT, POST and DELETE in our ApiService layer.

@Injectable()
export class ApiService {
 
    constructor(private http:HttpClient) {}
 
    ...
 
    createEmployee(employee) {
        let body = JSON.stringify(employee);
        return this.http.post('/api/employee/', body, httpOptions);
    }

    updateEmployee(employee) {
        let body = JSON.stringify(employee);
        return this.http.put('/api/employee/' + employee.id, body, 
                             httpOptions);
    }

    deleteEmployee(employee) {
        return this.http.delete('/api/employee/' + employee.id);
    }
 
}

Retrying – retry GET API call on fail

Sometimes the error is transient and will go away automatically if you try again. For example, network interruptions are common in mobile scenarios, and trying again may produce a successful result.

The RxJS library offers several retry operators that are worth exploring. The simplest is called retry() and it automatically re-subscribes to a failed Observable a specified number of times. Re-subscribing to the result of an HttpClient method call has the effect of reissuing the HTTP request.

Pipe it onto the HttpClient method result just before the error handler.

getConfig() {
  return this.http.get<Config>(this.configUrl)
    .pipe(
      retry(3), // retry a failed request up to 3 times
      catchError(this.handleError) // then handle the error
    );
}

Executing multiple concurrent HTTP requests – using forkJoin ()

Many times, we need to load data from more than one source, and we need to delay the post-loading logic until all the data has loaded. ReactiveX Observables provide a method called forkJoin() to wrap multiple Observables. Its subscribe() method sets the handlers on the entire set of Observables.

...

@Injectable()
export class ApiDemoService {
 
    constructor(private http:HttpClient) {}
 
    // Uses Observable.forkJoin() to run multiple concurrent http.get() 
    // requests.
    // The entire operation will result in an error state if any single 
    // request fails.
    
    getEmployeesAndRole() {
        return Observable.forkJoin(
        this.http.get('/api/employees'),
        this.http.get('/api/roles')
        );
    }
}

Now subscribe to the service

export class AppComponent {
 
+  public employees;
+  public roles;

 
+  getEmployeesAndRole() {
+    this._apiDemoService.getEmployeesAndRole().subscribe(
+      data => {
+        this.employees= data[0]
+        this.roles= data[1]
+      }
+      // No error or completion callbacks here. They are optional, but
+      // you will get console errors if the Observable is in an error state.
+    );
+  }
 
}

Summary

In this tutorial we learnt about Angular REST API Calls. We saw examples of all the CRUD api calls in angular, we saw how to retry an api call on fail and we also learnt how to make multiple concurrent HTTP requests using forkJoin Observable method.
I hope you liked it !


@angular/core APIs

Implements Angular’s core functionality, low-level services, and utilities.

Some of the core classes/interfaces/functions are as follows :

1. EventEmitter

It is a Class, In Angular, a component can emit an event using @Output and EventEmitter. Both are parts of the @angular/core.
It emit custom events synchronously or asynchronously, and register handlers for those events by subscribing to an instance.

appchild.component.ts

import { Component, EventEmitter, Output } from '@angular/core';
@Component({
    selector: 'app-child',
    template: `<button class='btn btn-primary' (click)="valueChanged()">Click me</button> `
})
export class AppChildComponent {
    @Output() valueChange = new EventEmitter();
    Counter = 0;
    valueChanged() { // You can give any function name
        this.counter = this.counter + 1;
        this.valueChange.emit(this.counter);
    }
}

to emit values in the parent component.

2. OnDestroy

It is an interface, it is a lifecycle hook that is called when a directive, pipe, or service is destroyed. Use for any custom cleanup that needs to occur when the instance is destroyed.

// its own Definition

interface OnDestroy {
  ngOnDestroy(): void
}
// Usage of ngOnDestroy()

@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements OnDestroy {
  ngOnDestroy() {
    // ...
  }
}

3. OnInit

It is an interface, it is a lifecycle hook that is called after Angular has initialized all data-bound properties of a directive. Define an ngOnInit() method to handle any additional initialization tasks.
It is invoked only once when the directive is instantiated.

// its own Definition

interface OnInit {
  ngOnInit(): void
}
// Usage of ngOnInit()

@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements OnInit {
  ngOnInit() {
    // ...
  }
}

4. ViewChild

It is one of the decorators, it is a Property decorator that configures a view query. The change detector looks for the first element or the directive matching the selector in the view DOM. If the view DOM changes, and a new child matches the selector, the property is updated.

// EXAMPLE

import {Component, Directive, Input, ViewChild} from '@angular/core';

@Directive({selector: 'pane'})
export class Pane {
  @Input() id !: string;
}

@Component({
  selector: 'example-app',
  template: `
    <pane id="1" *ngIf="shouldShow"></pane>
    <pane id="2" *ngIf="!shouldShow"></pane>

    <button (click)="toggle()">Toggle</button>

    <div>Selected: {{selectedPane}}</div>
  `,
})
export class ViewChildComp {
  @ViewChild(Pane, {static: false})
  set pane(v: Pane) {
    setTimeout(() => { this.selectedPane = v.id; }, 0);
  }
  selectedPane: string = '';
  shouldShow = true;
  toggle() { this.shouldShow = !this.shouldShow; }
}

Summary

In this tutorial we learnt about the angular core APIs , few classes, interfaces and functions.
Hope you like it !


Angular – RxJS Classes and functions

RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using observables that makes it easier to compose asynchronous or callback-based code.

RxJS provides an implementation of the Observable type, The library also provides utility functions for creating and working with observables.

RxJs Classes & functions

1. Observable

A representation of any set of values over any amount of time. This is the most basic building block of RxJS.

import { Observable } from 'rxjs';
 
const foo = new Observable(subscriber => {
  console.log('Hello');
  subscriber.next(42);
});
 
foo.subscribe(x => {
  console.log(x);
});
foo.subscribe(y => {
  console.log(y);
});

OUTPUT

"Hello"
42
"Hello"
42

2. BehaviorSubject

Requires an initial value and emits the current value to new subscribers

import { BehaviorSubject } from 'rxjs';

const subject = new BehaviorSubject(11);

// two new subscribers will get initial value => output: 11, 11
subject.subscribe(console.log);
subject.subscribe(console.log);

// two subscribers will get new value => output: 22, 22
subject.next(22);

// new subscriber will get latest value (22) => output: 22
subject.subscribe(console.log);

// all three subscribers will get new value => output: 33, 33, 33
subject.next(33);

// OUTPUT :: 11, 11, 22, 22, 22, 33, 33, 33

3. combineLatest

Combines multiple Observables to create an Observable whose values are calculated from the latest values of each of its input Observables.

import { combineLatest, timer } from 'rxjs';

const firstTimer = timer(0, 1000); // emit 0, 1, 2... after every second, starting from now
const secondTimer = timer(500, 1000); // emit 0, 1, 2... after every second, starting 0,5s from now

const combinedTimers = combineLatest(firstTimer, secondTimer);
combinedTimers.subscribe(value => console.log(value));

// OUTPUT Logged
// [0, 0] after 0.5s
// [1, 0] after 1s
// [1, 1] after 1.5s
// [2, 1] after 2s

Summary

In this tutorial we learnt about few important classes of RxJS and its functions.
Hope you like it !


Angular – RxJS Operators

RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using observables that makes it easier to compose asynchronous or callback-based code.

RxJS provides an implementation of the Observable type, The library also provides utility functions for creating and working with observables.

 These utility functions can be used for:

  • Converting existing code for async operations into observables
  • Iterating through the values in a stream
  • Mapping values to different types
  • Filtering streams
  • Composing multiple streams

RxJS Operators

1. of() – Emit variable amount of values in a sequence and then emits a complete notification.

import { of } from 'rxjs';
//emits any number of provided values in sequence
const source = of(1, 2, 3, 4, 5);
//output: 1,2,3,4,5
const subscribe = source.subscribe(val => console.log(val));

2. Tap() – Transparently perform actions, such as logging.

import { of } from 'rxjs';
import { tap, map } from 'rxjs/operators';

const source = of(1, 2, 3, 4, 5);
// transparently log values from source with 'tap'
const example = source.pipe(
  tap(val => console.log(`BEFORE MAP: ${val}`)),
  map(val => val + 10),
  tap(val => console.log(`AFTER MAP: ${val}`))
);

//'tap' does not transform values
//output: 11...12...13...14...15
const subscribe = example.subscribe(val => console.log(val));

OUTPUT

BEFORE MAP: 1
AFTER MAP: 11
11
BEFORE MAP: 2
AFTER MAP: 12
12
BEFORE MAP: 3
AFTER MAP: 13
13

3. map() – Apply projection with each value from source.

import { from } from 'rxjs';
import { map } from 'rxjs/operators';

//emit (1,2,3,4,5)
const source = from([1, 2, 3, 4, 5]);
//add 10 to each value
const example = source.pipe(map(val => val + 10));
//output: 11,12,13,14,15
const subscribe = example.subscribe(val => console.log(val));

OUTPUT

11
12
13
14
15

4. debounceTime() – Discard emitted values that take less than the specified time between output.

import { fromEvent } from 'rxjs';
import { debounceTime, map } from 'rxjs/operators';

// elem ref
const searchBox = document.getElementById('search');

// streams
const keyup$ = fromEvent(searchBox, 'keyup');

// wait .5s between keyups to emit current value
keyup$
  .pipe(
    map((i: any) => i.currentTarget.value),
    debounceTime(500)
  )
  .subscribe(console.log);

OUTPUT – On every keyup press, it waits for 500 milisec to log in console and discards the button press in between.

Note :- that in the call stack, it’s Observable.subscribe that kicks everything off. Because observables tend to be lazy, no data will flow through the pipe and map until we subscribe to the observable.

5. startWith() – Returns an Observable that emits the items you specify as arguments before it begins to emit items emitted by the source Observable.

import { of } from 'rxjs';
import { startWith } from 'rxjs/operators';

of(1,2,3)
  .pipe(startWith("first", "second"))
  .subscribe(x => console.log(x));

// OUTPUT ::
//   "first"
//   "second"
//   1
//   2
//   3

6. distinctUntilChanged() – Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item.

import { of } from 'rxjs';
import { distinctUntilChanged } from 'rxjs/operators';

of(1, 1, 2, 2, 2, 2, 2, 1, 1, 2, 3, 3, 4).pipe(
    distinctUntilChanged(),
  )
  .subscribe(x => console.log(x)); // OUTPUT : 1, 2, 1, 2, 3, 4

7. takeUntil() – Emits the values emitted by the source Observable until a notifier Observable emits a value.

import { fromEvent, interval } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

const source1 = interval(1000);
const clicks = fromEvent(document, 'click');
const result = source1.pipe(takeUntil(clicks));
result.subscribe(x => console.log(x));

// OUTPUT:
// It will keep on logging in console number like 0, 1, 2, 3 and so on 
// until a mouse click is seen.

Pipe()

Unlike tap,map, which are operators, pipe is a method on Observable which is used for composing operators. pipe was introduced to RxJS in v5.5.

Example :

converting this

of(1,2,3).map(x => x + 1).filter(x => x > 2);

into this

of(1,2,3).pipe(
  map(x => x + 1),
  filter(x => x > 2)
);

Summary

In this tutorial we learnt one of the most important topics in RxJS, we learnt RxJs Operators , its usage with examples.
Hope you liked it !


How to create a form in angular

In this tutorial we will learn how to create a form in angular 7 application. We will make a form like below.

angular-form-contact-form

Before we head to create the form, let’s understand the basics:

There are 2 types of forms :
1. Template driven forms
2. Model driven or Reactive forms 

1. Template driven forms

The template driven approach makes use of built-in directives to build forms such as ngModelngModelGroup, and ngForm available from the FormsModule module.

When to use ?

  • where forms are small
  • Simple validations
  • migrating from angular 1 to angular 2

Advantage:

  • easier to create
  • less code

2. Model driven or Reactive forms

The model driven approach of creating forms in Angular 6 makes use of FormControlFormGroup and FormBuilder available from the ReactiveFormsModule module.

When to use ?

  • Where forms are big
  • validations are complex

Reactive forms have majorily two classes:

  • FormGroup : can be considered as a collection of FormControls and other FormGroups
  • FormControl : to bind the properties with the html elements

At first, we will create an instance of FormGroup class and link it to the html form. Then, we will create a number of instances of FormControl as many number of form elements.

Let’s Begin !

Step 1: Registering the reactive forms module in app.module.ts

 import { ReactiveFormsModule } from '@angular/forms';

and

 imports: [ BrowserModule, AppRoutingModule, ReactiveFormsModule ], 

Step 2: Creating a FormGroup in app.component.ts

import { Component, OnInit } from '@angular/core';
import {FormGroup, FormControl} from '@angular/forms';
  
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent{
  title = 'my-dream-app';
  contactForm : FormGroup;
  
  constructor(){}
  ngOnInit(){
    this.contactForm = new FormGroup({
      name: new FormControl(),
      email: new FormControl()
    });
  }
  
  onSubmit(): void{
    console.log(this.contactForm.value);
  }
}

we will print the values entered in the form to the console log.

Step 3: Associating FormGroup with the HTML view

<div class="col-lg-4" >
  <form [formGroup]="contactForm" (ngSubmit)="onSubmit()" class="form-horizontal">
    <h3 class="panel-title">Contact Form</h3>
    <div class="form-group">
      <label>Name</label>
      <input id="name" formControlName="name" type="text" class="form-control">
    </div>
    <div class="form-group">
      <label>Email</label>
      <input id="email" formControlName="email" type="text" class="form-control">
    </div>
    <div>
      <button type="submit" class="btn-primary">Submit</button>
    </div>
  </form>
</div>

Output

angular-form-contact-form-output

Summary

In this tutorial, we learnt about how to create a form in angular application and different types of form.
Hope you liked it!


How to create a component in angular

In this tutorial we will understand how to create a component in angular application. We have already seen what is an angular component though, but we will look into it again. In Angular each functionality can be made as a component which can be used in the entire application just by importing it. So now we will look into the steps to create a component in angular.

Let’s Begin ! – Just 2 Steps

Step 1 :

create a new directory inside app directory for better management of components(not mandatory)

> mkdir contact

Step 2 :

Now, create component by using command as below

> ng g c contact –flat

-g : to generate

-c : for component

–flat in an option used to stop create a directory of same name as the name given in the above command, and create all files in the current directory. It puts the file in src/app instead of its own folder.

So the above command creates 4 files as shown below in this snapshot.

create-angular-component-using-angular-cli

This creates 4 files :

contact.component.html file : file write the html content of your page exists.

contact.component.spec.ts : file where you have the test cases

contact.component.ts : file where you write the functionality and logics in this typescript.

contact.component.css : file where you write the css content of the page.

 Next, Include this component in main app.component.html 

by including the tag in app.component.html as per the selector created in contact.component.ts

<app-contact></app-contact>
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-contact',
  templateUrl: './contact.component.html',
  styleUrls: ['./contact.component.css']
})
export class ContactComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }
}

Summary

In this tutorial, we learnt how to create a component in angular application and add the created component using its html selector tag to any other component like AppComponent here. Enjoy learning Angular.
Hope you liked it!


How to add bootstrap and other js in angular application

In this tutorial we will understand how to add bootsrap css in angular app.

After creating the angular basic app using ng new my-dream-app install the bootstrap using the below command.

1. Install bootsrap using npm cli

> npm install bootstrap –save

Type this command from your project directory eg: (c:\workspace\my-dream-app)

install-bootstrap-css-in-angular

Note: In case you see a Warning as below in the snapshot, it means you need to navigate to your project structure and then execute the bootstrap install command, if you see a warning of package.json no such file warning it simply means you must install bootstrap from this directory where the file is present.

install-bootstrap-css-in-angular

2. Add bootstrap css entry in angular.json

Open angular.json file, locate styles and add bootstrap file path to the styles section. Like this,

angular-json-styles-add-bootstrap

3. Verify – bootstrap has been installed successfully or not?

Let’s add a table with few extra bootstrap classes to see bootstrap is working fine or not

In your app.component.html

add the following html table code:

<div class="container">
  <table class="table table-dark table-hover table-striped">
    <thead class="thead-light">
      <tr>
        <th>Name</th>
        <th>Age</th>       
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>Jack</td>
        <td>30</td>
      </tr>
      <tr>
        <td>Jill</td>
        <td>31</td>       
      </tr>
      <tr>
        <td>Robert</td>
        <td>32</td>       
      </tr>
    </tbody>
  </table>
</div>

Now You would see this in your browser: localhost:4200

angular-bootstrap-css-table

AND earlier without Bootstrap, it would look like as shown below:

angular-table-without-bootstrap-css

Summary

In this tutorial, we learnt about how to add bootstrap in angular project and how to make use of it by adding a simple bootsrap css classes in html table, Enjoy using bootstrap with angular now, it makes life easier.
Hope you liked it!


Angular app Files and its explanation / Files Explanation

In this tutorial we will understand the angular file-structure of a project and see each default file, folder created and its uses.

angular-project-file-structure-visual-studio-code

Files used in Angular 7 App folder

  • src folder: This is the folder which contains the main code files related to your angular application.
  • app folder: The app folder contains the files, you have created for app components.
  • app.component.css: This file contains the cascading style sheets code for your app component.
  • app.component.html: This file contains the html file related to app component. This is the template file which is used by angular to do the data binding.
  • app.component.spec.ts: This file is a unit testing file related to app component. This file is used along with other unit tests. It is run from Angular CLI by the command ng test.
  • app.component.ts: This is the most important typescript file which includes the view logic behind the component.
  • app.module.ts: This is also a typescript file which includes all the dependencies for the website. This file is used to define the needed modules to be imported, the components to be declared and the main component to be bootstrapped.
  • e2e folder: end-to-end testing files for the project are contained here.

Other Important files

  • package.json: This is npm configuration file. It includes details about your website’s package dependencies along with details about your own website being a package itself.
  • package-lock.json: This is an auto-generated and modified file that gets updated whenever npm does an operation related to node_modules or package.json
  • angular.json: It is very important configuration file related to your angular application. It defines the structure of your app and includes any settings associated with your application. Here, you can specify environments on this file (development, production). This is the file where we add Bootstrap file to work with Angular 7.
  • .gitignore: This file is related to the source control git.
  • .editorconfig: This is a simple file which is used to maintain consistency in code editors to organize some basics such as indentation and whitespaces.
  • assets folder: This folder is a placeholder for resource files which are used in the application such as images, locales, translations etc.
  • environments folder: The environments folder is used to hold the environment configuration constants that help when building the angular application. The constants are defined in 2 separate .ts files (environment.ts and environment.prod.ts), where these constants are used within the angular.json file by the Angular CLI. For example, if you run the ng build command, it will build the application using the development environment settings, whereas the command ng build ?prod will build the project using the production environment settings.
  • browserslist: This file is used by autoprefixer that adjusts the CSS to support a list of defined browsers.
  • favicon.ico: This file specifies a small icon that appears next to the browser tab of a website.
  • index.html: This is the entry file which holds the high level container for the angular application.
  • karma.config.js: This file specifies the config file for the Karma Test Runner, Karma has been developed by the AngularJS team which can run tests for both AngularJS and Angular 2+
  • main.ts: As defined in angular.json file, this is the main ts file that will first run. This file bootstraps (starts) the AppModule from app.module.ts , and it can be used to define global configurations.
  • polyfills.ts: This file is a set of code that can be used to provide compatibility support for older browsers. Angular 7 code is written mainly in ES6+ language specifications which is getting more adopted in front-end development, so since not all browsers support the full ES6+ specifications, pollyfills can be used to cover whatever feature missing from a given browser.
  • styles.css: This is a global css file which is used by the angular application.
  • tests.ts: This is the main test file that the Angular CLI command ng test will use to traverse all the unit tests within the application and run them.
  • tsconfig.json: This is a typescript compiler configuration file.
  • tsconfig.app.json: This is used to override the tsconfig.json file with app specific configurations.
  • tsconfig.spec.json: This overrides the tsconfig.json file with app specific unit test configurations.

Summary

In this tutorial, we learnt about the file structure of the angular application, it’s various files and folder structures and the type of information it stores.
Hope you liked it!


Angular – Routing

In this tutorial we will learn about Angular Routing, Angular Routing is one of the important functionality in angular, it makes navigation faster.

Routing is a component in angular which is used for navigation in the application to navigate from one view to the other.

Steps to implement routing in your angular application

Step 1: add base tag

  <base href="/">

Step 2: create or there already exist a routing module

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
  
const routes: Routes = [];
  
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

2 most important things to note here:

  1. create a routes constant array
  2. In the imports add the RouterModule.forRoot(routes)

Step 3: In the src/app/app.module.ts add import

import { AppRoutingModule } from './app-routing.module';

and add it in the Module imports as well

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
  })

Step 4: The router-outlet tag in app.component.html

<router-outlet></router-outlet>

The < router-outlet > tells the router where to display routed views.

The RouterOutlet is one of the router directives that became available to the AppComponent because AppModule imports AppRoutingModule which exported RouterModule.

Step 5: Add the anchor tags with routerLink and routerLinkActive directives to make the routing functional. Add this anchor tags in the page from where you want to access any other view.

<a routerLink=”/contact-form”></a>

Lets Understand with an Example

In this example we will be able to Add routes and open a contact form :

  1. ON – click of a button &
  2. ON – accessing the link directly in browser
angular-routing-on-click-of-a-button

Step 1: Lets create a component called contact component

 >ng g c contact
create-component-contact

In contact.component.html file add the below html for creating a simple contact form

<p>
contact works!
</p>

<div class="col-lg-4" >
<form [formGroup]="contactForm" (ngSubmit)="onSubmit()" class="form-horizontal">
  <h3 class="panel-title">Contact Form</h3>
  <div class="form-group">
    <label>Name</label>
    <input id="name" formControlName="name" type="text" class="form-control">
  </div>
  <div class="form-group">
    <label>Email</label>
    <input id="email" formControlName="email" type="text" class="form-control">
  </div>
  <div>
    <button type="submit" class="btn-primary">Submit</button>
  </div>
</form>
</div>

Step 2: create a constant of path in AppRoutingModule & also import the ContactComponent

Below is the code of AppRoutingModule

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ContactComponent } from './contact/contact.component';
  
const routes: Routes = [
  {
    path : 'contact-form', component : ContactComponent
  }
];
  
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Step 3: add anchor tag in app.component.html to call the contact form page

add the below html block in app.component.html page, you can add it anywhere in this file.

<div style="text-align: center">
    <button><a routerLink="contact-form" >Click to open form</a></button>
</div>
<hr>

Step 4: OUTPUT view of the page

Open url localhost:4200 , you will see this page below

angular-routing-on-click-of-a-button-executed

Now, Click on the button “Click to open form” as shown in the above snapshot, Or directly open the url “localhost:4200/contact-form” this will open the contact form page as shown below in the snapshot.

angular-routing-from-the-url

Summary

You are now good to go with Routing in angular, here we created a simple contact form page which we called on click of a button. Benefit of using angular routing is that it makes the navigation faster, simpler within the application in between different views or pages without refreshing the entire page.
Hope you liked it!


Angular Installation steps and create First angular app

Steps – Very simple to follow

1. Install Nodejs

Node.js provides the node package manager which manages the dependencies to run an angular Project. Node.js serves as the run time environment to run javascript based frameworks and applications.

GOTO Node js official link to download and install Node.js https://nodejs.org/en/

Preferably you can download the LTS version as it is the LTS version which has long term support.

nodejs-installation

TEST for successful node installation :

 Type in cmd prompt > node -v > it will give you a version is installed correctly
check-node-installation-version

2. Install Angular CLI using npm

Type this command in command prompt :

 > npm install -g @angular/cli
install-angular-cli-with-npm

Verify angular cli is installed correctly or not

 Type > ng -v
angular-cli-version-check

Great ! – now you have successfully installed angular on your machine. Goto Step 3 and create your first angular app, it’s super simple.

3. Create Angular Basic app – using one single command

 > ng new my-dream-app
create-angular-app-from-cli
It will ask a few questions like:
 Would you like to add routing to your app ? click yes or no
Which stylesheet format would you like to use ? CSS/Less/Sass etc, choose one from the options 

Voila !

You have created your first angular app

Run it …….

Type in command prompt/shell :

> cd my-dream-app
> ng serve 
start-angular-app-ng-serve

now open your web browser and type the url :

localhost:4200

my-dream-angular-app-localhost

Congrats ! – We are done with installing and creating our first basic angular app.

Read Next tutorial -> to Understand the File structure and use of each file in angular app.

Summary

In this tutorial, we learn Step by Step how we can create very first angular app. We Suggest try to follow this tutorial and get started with angular app.
Hope you liked it!