Angular 9 Example Tutorial

In this tutorial, we will learn how to create a simple hello world angular 9 web application.

What we will build?

Basically, we will create two projects:
  1. springboot-helloworld-application: This project is used to develop simple RESTFul API using Spring Boot 2.
  2. angular9-helloworld-example-tutorial: This project is used to develop single page application using Angular 9 as front-end technology. This Angular 9 application consumes Restful API developed and exposed by a springboot-helloworld-application project.

REST API using Spring Boot

We will create a simple RESTful web service with below endpoint using Spring boot:
http://localhost:8080/hello-world/api/v1/greeting
This REST API returns below JSON:
{"id":11,"content":"Hello, World!"}
I have already created a step by step tutorial to develop a simple RESTFul web service application using Spring Boot. You can refer at https://www.javaguides.net/2019/04/spring-boot-2-hello-world-example.html
Make sure that you have created the Spring boot REST API application using the above tutorial and run it on http://localhost:8080/.
Once your Spring boot REST API app is up and running then let's develop an angular client application using Angular 9.

Now, we will create a step by step Angular 9 Application to consume this web service.

Develop an Angular 9 App

Let's develop a step by step Web Application using Angular 9 which consumes below greeting Rest web service.
http://localhost:8080/hello-world/api/v1/greeting
I assume that you have installed Node.js. Now, we need to check the Node.js and NPM versions. Open the terminal or Node command line then type these commands.
C:\Angular>node -v
v10.15.3

C:\Angular>npm -v
6.9.0

Install the latest version of Angular CLI 9

To install or update Angular 9 CLI, type this command in the terminal:
npm install -g @angular/[email protected]
Note that we are installing Angular CLI 9.
Now, let's check the latest version of Angular CLI:
C:\Angular\angular9-springboot-crud-tutorial>ng --version
     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/


Angular CLI: 9.0.0-rc.7
Node: 10.15.3
OS: win32 x64

Angular:
...
Ivy Workspace:

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.900.0-rc.7
@angular-devkit/core         9.0.0-rc.7
@angular-devkit/schematics   9.0.0-rc.7
@schematics/angular          9.0.0-rc.7
@schematics/update           0.900.0-rc.7
rxjs                         6.5.3

Create an Angular 9 App using Angular CLI 9

The Angular CLI is a command-line interface tool that you use to initialize, develop, scaffold, and maintain Angular applications.
If you are new to Angular CLI then check out official documentation at https://cli.angular.io.
Let's use the below command to generate an Angular 9 Client application. We name this project as "angular9-helloworld-example-tutorial".
ng new angular9-helloworld-example-tutorial

C:\Ramesh_Study\Angular\angular 9>ng new angular9-helloworld-example-tutorial
? Would you like to add Angular routing? Yes
? Which stylesheet format would you like to use? CSS
CREATE angular9-helloworld-example-tutorial/angular.json (3807 bytes)
CREATE angular9-helloworld-example-tutorial/package.json (1373 bytes)
CREATE angular9-helloworld-example-tutorial/README.md (1055 bytes)
CREATE angular9-helloworld-example-tutorial/tsconfig.json (535 bytes)
CREATE angular9-helloworld-example-tutorial/tslint.json (1953 bytes)
CREATE angular9-helloworld-example-tutorial/.editorconfig (246 bytes)
CREATE angular9-helloworld-example-tutorial/.gitignore (631 bytes)
CREATE angular9-helloworld-example-tutorial/browserslist (429 bytes)
CREATE angular9-helloworld-example-tutorial/karma.conf.js (1048 bytes)
CREATE angular9-helloworld-example-tutorial/tsconfig.app.json (210 bytes)
CREATE angular9-helloworld-example-tutorial/tsconfig.spec.json (270 bytes)
CREATE angular9-helloworld-example-tutorial/src/favicon.ico (948 bytes)
CREATE angular9-helloworld-example-tutorial/src/index.html (319 bytes)
CREATE angular9-helloworld-example-tutorial/src/main.ts (372 bytes)
CREATE angular9-helloworld-example-tutorial/src/polyfills.ts (2838 bytes)
CREATE angular9-helloworld-example-tutorial/src/styles.css (80 bytes)
CREATE angular9-helloworld-example-tutorial/src/test.ts (642 bytes)
CREATE angular9-helloworld-example-tutorial/src/assets/.gitkeep (0 bytes)
CREATE angular9-helloworld-example-tutorial/src/environments/environment.prod.ts (51 bytes)
CREATE angular9-helloworld-example-tutorial/src/environments/environment.ts (662 bytes)
CREATE angular9-helloworld-example-tutorial/src/app/app-routing.module.ts (246 bytes)
CREATE angular9-helloworld-example-tutorial/src/app/app.module.ts (393 bytes)
CREATE angular9-helloworld-example-tutorial/src/app/app.component.html (25705 bytes)
CREATE angular9-helloworld-example-tutorial/src/app/app.component.spec.ts (1149 bytes)
CREATE angular9-helloworld-example-tutorial/src/app/app.component.ts (240 bytes)
√ Packages installed successfully.

Create Angular Service & Components

Let's auto-generate the service and components using Angular CLI. Change your project directory to angular9-helloworld-example-tutorial\src\app and run the following commands:
- ng g s hello-world
– ng g c hello-world
– ng g c menu
Create a modal folder and run the following command to generate Message.ts typescript class:
– ng generate class Message

Angular Project Structure

Below screenshot shows our angular project structure:

Integrate Bootstrap with Angular

Use NPM to download Bootstrap & JQueryBootstrap and jQuery will be installed into the node_modules folder.
npm install bootstrap jquery --save
Configure installed Bootstrap & JQuery in an angular.json file:
...
 
"styles": [
  "src/styles.css",
  "node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"scripts": [
  "node_modules/jquery/dist/jquery.min.js",
  "node_modules/bootstrap/dist/js/bootstrap.min.js"
]
 
...
If bootstrap.min.css won't work then import this bootstrap.min.css in a style.css file like this:
/* You can add global styles to this file, and also import other style files */
@import url(https://unpkg.com/[email protected]/dist/css/bootstrap.min.css)

hello-world.service.ts -> HelloWorldService

The HelloWorldService will be used to get the data from the backend by calling spring boot APIs. Update the hello-world.service.ts file inside the src/app directory with the following code to it -
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { MessageModel } from '../model/Message';

@Injectable({
    providedIn: 'root'
})
export class HelloWorldService {
    constructor(private http: HttpClient) {
    }
    executeHelloWorldService() {
        return this.http.get<MessageModel>('http://localhost:8080/hello-world/api/v1/greeting');
    }
}

Model -> Message.ts

Let's create a Message model typescript to hold REST API response data and display on HTML template -
export class MessageModel {
    id: number;
    content: string;
    constructor(private _id: number, public message: string) {
        this.id = _id;
        this.content = message;
    }
}

hello-world.component.ts -> HelloWorldComponent 

The hello-world.component.ts defines the logic associated with HelloWorldComponent.
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { HelloWorldService } from '../service/hello-world.service';

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

  welcomeMessage = '';

  constructor(private route: ActivatedRoute,
    private router: Router, private helloWorldService: HelloWorldService) { }

  ngOnInit() {
    this.helloWorldService.executeHelloWorldService().subscribe((res) => {
      this.welcomeMessage = res.content;
    });
  }
}

hello-world.component.html -> HelloWorldComponent

The hello-world.component.html defines the HTML template associated with the HelloWorldComponent.
<div class="container">
  Message from server ->  <h1>{{this.welcomeMessage}}</h1>
</div>

menu.component.ts -> MenuComponent

The menu.component.ts file defines the logic for the menu component, named MenuComponent.
import { Component, OnInit } from '@angular/core';

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

  welcomeMessage = 'Test';

  constructor() { }

  ngOnInit() {

  }
}

menu.component.html -> MenuComponent

The menu.component.html defines the HTML template associated with the MenuComponent.
<header>
  <nav class="navbar navbar-expand-md navbar-dark bg-dark">
      <div><a href="https://www.javaguides.net" class="navbar-brand">JavaGuides</a></div>
      <ul class="navbar-nav">
          <li><a class="nav-link" href="/hello-world">Hello World Tab</a></li>
      </ul>
  </nav>
</header>

app.module.ts -> AppModule

The app.module.ts file defines the root module, named AppModule, that tells Angular how to assemble the application. Initially declares only the AppComponent. As you add more components to the app, they must be declared here.
Every application has at least one Angular module, the root module that you bootstrap to launch the application. By convention, it is usually called AppModule. Here is the code for AppModule:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HelloWorldService } from './service/hello-world.service';
import { MenuComponent } from './menu/menu.component';
import { HelloWorldComponent } from './hello-world/hello-world.component';

@NgModule({
  declarations: [
    AppComponent,
    MenuComponent,
    HelloWorldComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
  ],
  providers: [
    HelloWorldService,
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

app-routing.module.ts -> AppRoutingModule

The app-routing.module.ts file defines the routing configuration in AppRoutingModule for Angular app:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HelloWorldComponent } from './hello-world/hello-world.component';

const routes: Routes = [
  {path: '', component: HelloWorldComponent},
  {path: 'hello-world', component: HelloWorldComponent},
];

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

app.component.ts -> AppComponent

The app.component.ts file defines the logic for the app's root component, named AppComponent. The view associated with this root component becomes the root of the view hierarchy as you add components and services to your application.
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'frontend-spring-boot-angular-hello-world-example';
}

app.component.html -> AppComponent

The app.component.html file defines the HTML template associated with the root AppComponent.
<app-menu></app-menu>
<router-outlet></router-outlet>

npm package.json - Configure Dependencies

Path: /package.json 
The package.json file contains project configuration information including package dependencies which get installed when you run npm install.
Note that angular version ~9.0.0-rc.7 in the dependencies section in the below file.
{
  "name": "angular9-helloworld-example-tutorial",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~9.0.0-rc.7",
    "@angular/common": "~9.0.0-rc.7",
    "@angular/compiler": "~9.0.0-rc.7",
    "@angular/core": "~9.0.0-rc.7",
    "@angular/forms": "~9.0.0-rc.7",
    "@angular/platform-browser": "~9.0.0-rc.7",
    "@angular/platform-browser-dynamic": "~9.0.0-rc.7",
    "@angular/router": "~9.0.0-rc.7",
    "bootstrap": "^4.4.1",
    "jquery": "^3.4.1",
    "rxjs": "~6.5.3",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.900.0-rc.7",
    "@angular/cli": "~9.0.0-rc.7",
    "@angular/compiler-cli": "~9.0.0-rc.7",
    "@angular/language-service": "~9.0.0-rc.7",
    "@types/node": "^12.11.1",
    "@types/jasmine": "~3.5.0",
    "@types/jasminewd2": "~2.0.3",
    "codelyzer": "^5.1.2",
    "jasmine-core": "~3.5.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage-istanbul-reporter": "~2.1.0",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.2",
    "protractor": "~5.4.2",
    "ts-node": "~8.3.0",
    "tslint": "~5.18.0",
    "typescript": "~3.6.4"
  }
}

Main Index Html File

Path: /src/index.html
The main index.html file is the initial page loaded by the browser that kicks everything off. Webpack bundles all of the javascript files together and injects them into the body of the index.html page so the scripts get loaded and executed by the browser.
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Angular9HelloworldExampleTutorial</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
</body>
</html>

Main (Bootstrap) File

Path: /src/main.ts
The main file is the entry point used by angular to launch and bootstrap the application.
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.error(err));

Running Angular 9 Application


Let's run the above developed Angular App with a command:
ng serve
By default, the Angular app runs on 4200 port but you can change default port with the following command:
ng serve --port 4204

Hit http://localhost:4200/ link in the browser will open the below page on the screen.

Comments