Getting started with Angular 18
We are going to make a Web Application.
In this tutorial we will use Angular version 18.0.2
We will start from scratch and we will follow Angular's best practices.
- Angular was created by Google.
- Angular is open source, so it's free to use
- Angular uses Typescript.
- Angular is a Frontend javascript framework.
How to do it ?
Here is a summary of what we are going to do.
- Installation of necessary tools
Node.js will be our javascript development platform.
No choice, without Node.js it won't work.
Visual studio Code will be our code editor.
The choice is totally arbitrary but for a Microsoft tool it's a little marvel
Git will be our software manager..
You will be able to use the source code of this tutorial
Angular CLI will be our handyman.
The best known and most used tool of the Angular Framework.
- Project initialization
We will use Angular CLI for setting up the project architecture,
using the best practices recommended by Google.
- Project Update
Check used dependencies and update them.
- Perform the Tests
Unit tests and the tools dedicated to them Karma and Jasmine.
Linting and improving code with ESLint.
- Environment
In version 15 the Angular team no longer integrates environment settings.
Very useful we will see how to declare and use them.
- Deployment
How to deploy your application on the internet.
- Source code
The complete project code is available on Github.
A picture paints a thousand words
The summary in pictures of what we are going to do
If you are in a hurry, below is a summary , otherwise go to the next step.
# Uninstall Angular CLI (in case an older version of Angular was installed)
npm uninstall -g @angular/cli
# Install Angular CLI specific version (latest if possible)
npm install -g @angular/cli@18.0.3
# Create a demo directory (the name here is arbitrary)
mkdir demo
# Go to this directory
cd demo
# Generate a project called angular-starter with manual choice of options (answer yes to everything)
ng new angular-starter
# Position yourself in the project
cd angular-starter
# run the application
npm run start
# Test the app in your browser
http://localhost:4200
And if you are less in a hurry it will start
We are going to do things seriously but we are not going to take ourselves seriously.
So let's go for a little humor and a lot of technique.
Installing the necessary tools
Before using Angular we need to install a number of software
- Node.js
Can't get Angular to work without it. - Visual StudioCode
This choice is arbitrary. - Git: Very useful but not essential
- Angular CLI: It's Angular's handyman
Installing Node.js
If you don't install it, Angular won't work.
In this regard Angular, React and Vuejs all three need Node.js.
The official website is here https://nodejs.org/fr/
This is what he tells us:
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine.
Its inventor Ryan Lienhart Dahl created it on May 27, 2009.
He had a specific idea in mind: the simplicity and speed of execution of programs written in javascript .
The choice of name is therefore not trivial.
- Node means knot
- JS stands for javascript
Node.js is thus the central point which will make it possible to execute programs written in javascript on the server side.
My God, It's Full of Stars
Node.js uses an npm tool (Node Package Manager)
Npm simplifies the life of the developer by allowing to publish and share Node.js libraries.
Npm notably makes it possible to simplify the installation, update or uninstallation of these libraries.
We can talk about libraries, packages or dependencies.
How to install it?
On the official site the download is accessible at the address https://nodejs.org/fr/download/
We will be using the LTS ( Long Term Support) version.
LTS means that the publisher generally guarantees us a maintenance period of at least two years,
- Node.js version 20.14.0 LTS
- npm (node package manager) version 10.8.1
This is a typical installation.
- Choose your operating system.
- Download the program and run it.
Once the installation is complete, we can verify that Node.js is installed on our workstation.
# Checking Node.js and npm version (method 1)
node --version
npm --version
# Checking Node.js and npm version (method 2)
node -v
npm -v
# npm update
npm install npm -g
# Checking npm update
npm -v
How do I know Node.js is working?
We will check that Node.js is working and that it allows you to run a javascript program.
Let's go to Wikipedia https://fr.wikipedia.org/wiki/Node.js
Let's test the example program "a Hello Word" that he offers us.
Create an index.js file with a code editor (notepad will do).
Copy the following sample code
const { createServer } = require('http');
// Création du serveur
const server = createServer((request, response) => {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World\n');
});
server.listen(3000, () => console.log(`Adresse du serveur : http://localhost:3000`));
All that remains is to carry out the tests
# Running javascript program
node index.js
# Verification in the browser
http://localhost:3000
Installing Visual Studio Code
Visual Studio Code is the editor used in most Angular conferences.
It is notably used by John Papa one of the best Angular lecturers and author of the Angular guides
https://github.com/johnpapa/angular-styleguide
In the rest of the tutorial we will therefore use Visual Studio Code .
VS code is a code editor developed by Microsoft for Windows, Linux and OS X.
Let's proceed with the installation.
The official website is here
We will be using the latest version 1.89.1 download here
Installation is as easy as Node.js.
You choose your operating system, download the program and run it.
The Visual Studio Code icon will allow us to launch VS Code.
What we will do in the Initialization with Angular CLI part
Installing Git
Writing a Web Application is like writing a book.
As time passes, the number of pages increases.
From a few hundred you can go to thousands of pages.
The number of modifications becomes considerable and to navigate it is not an easy task.
To manage this problem, tools have been developed.
These are the version management software (or VCS in English, for version control system).
The best known is Git . It was created by Linus Torval the creator of Linux.
It will allow us to manage our source code and its different versions.
And above all to be able to share this source code, thus making it possible to work with several people.
Git will also allow you to use and test the source code of this tutorial.
Let's go to the installation.
The official website is at the following address https://git-scm.com/
Installation can be accessed here https://git-scm.com/download/win
Download the app then run it.
To check that Git is installed on your workstation, just run a command line.
# Version testing
git --version
Installing Angular CLI
Angular CLI stands for Angular Command Line Interface.
But that's mostly it.
The Angular handyman
And you might as well use the most recent version.
- Angular version 17.0.7
- Angular CLI version 17.0.7
The latest versions of these tools are available below
The installation procedure is detailed on the official Angular website
https://angular.io/cli
The method is described on the official website page.
I will detail this one.
- If a previous version was installed on your computer, you can uninstall it with the following command
# Uninstalling angular-cli
npm uninstall -g @angular/cli
Angular CLI is a library (or package).
We will install it with npm the node.js manager
You can install a specific version of angular or install the latest available by default.
# Installation of angular-cli latest version available
npm install -g @angular/cli
# Installing angular-cli specific version
npm install -g @angular/cli@18.0.3
# Installed version test
ng version
Initializing the project with Angular CLI
Angular is a comprehensive framework that covers a large number of features.
The documentation is particularly extensive and detailed.
We will try as often as possible to respect best practices (best practices) recommended by the angular team.
We can manually create each element of our application but the easiest way is to use Angular CLI
Create our application with Angular CLI
Angular CLI is a tool for initializing, developing and maintaining Angular applications.
The official site is here https://angular.dev/cli
And if you want to have the list of Angular CLI commands https://github.com/angular/angular-cli/wiki
To go faster, I'll give you an essential summary.
Angular CLI offers us a number of commands.
These commands save us from performing repetitive tasks.
The first command we are going to use is ng new or ng n
- She will create our application.
- It will generate all the files needed for this application.
- It will obviously follow the best practices recommended by the Google team.
We choose the name of our application (arbitrarily it will be here angular-starter )
We type the command ng new with the corresponding parameters
- We generate the project ( this part takes a few minutes )
- For a simpler understanding we will manage routing and sass in another tutorial.
- Disable Server side Rendering (default No)
- Choose the CSS type (default value)
- We position ourselves in the project
- We execute the project
Which give
# Generate a project called angular-starter with manual choice of options
ng new angular-starter
# Generate a project called angular-starter with default options
ng new angular-starter --defaults
# Position yourself in the project
cd angular-starter
# Execute
ng serve
# Automatically run and launch app in browser
ng serve -o
Angular CLI via ng serve command runs the project on a default port (4200).
It only remains to test the operation in a browser by launching the following url.
# Test
http://localhost:4200
Use our app with Visual Studio Code
Launch VS Code .
Open a folder in the angular-starter directory we created during initialization.
Then open the package.json file.
This contains a number of commands (or scripts) that we will be using throughout this tutorial.
Open a VS Code console (select View/Terminal) to run the following scripts
- npm run start : Runs the application in development mode.
- npm run build : Compiles the application in the dist directory.
- npm run test : Runs unit tests using the Karma framework.
Note for those nostalgic for previous versions:
The ng eject command (allowing to generate the webpack configuration) has been disabled.
It has been removed since version 8.
Configuration Format Management Sample Project
https://github.com/manfredsteyer/ngx-build-plus
In development mode if we want to customize the port, we just have to modify the start script in the package.json file.
For example to use port 4201 the script would be the following "start": " ng serve --port 4201 "
We will leave port 4200 modifiable at will for the rest of the tutorial.
"scripts": {
"ng": "ng",
"start": "ng serve --port 4200",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test"
},
Updating package.json
Node.js is the platform to develop our application.
Node.js is based on the use of libraries or dependencies.
Npm is the library manager (packages in English)
Updating an application and therefore its libraries is a perilous issue.
I'm going to show you that with Angular the notion of updating versions is essential.
It must be carried out with caution.
Update or not update
JavaScript libraries are constantly modified and updated by their designer.
When a new version is available it bears the name of release (release in English) and has a specific number.
If the library is open-source, you can see the latest versions available by going to the corresponding repository on Github and then going to Releases.
For example the different versions of Angular are accessible here
https://github.com/angular/angular/releases
The update schedule is here
https://angular.dev/reference/releases#versioning
Your past, your present and your future.
Note that versions 2 to 14 are no longer supported.
And the danger is obviously that all these updates alter the functioning of our application.
In any case, we cannot escape it; one day or another we will have to try to integrate them into our projects.
I will explain to you how I personally proceed.
« I didn't think that far ahead.. »
How do we do?
Let's use npm (Node Package Manager) the Node.js library manager.
Full documentation is here https://docs.npmjs.com/cli/outdated.html
npm allows us to check the versions of our libraries via the command
- npm outdated
This command checks the dependency registry to see if the installed packages are up to date.
It thus provides us with a list that we can control.
Noticed
Before checking the dependencies let's modify the package.json file
For each specified dependency remove the character ~ or ^
For example replace
- "rxjs": "~7.8.0",
- "tslib": "^2.3.0",
by
- "rxjs": "7.8.0",
- "tslib": "2.3.0",
To avoid possible errors, first delete the package-lock.json file and the node_modules directory.
Then reinstall the dependencies with npm install ( package-lock.json and node_modules are then recreated automatically).
You will understand why later in the paragraph it is time for the update.
# Checking versions of dependencies installed in node_modules
npm list --depth=0
# Checking available dependencies
npm outdated
Update results!
If I update the package.json file I find myself faced with 3 scenarios
- 1/ It works
It's not a party every day but since Angular 8 it's more and more often - 2/ It doesn't work, we try to debug without spending too much time on it.
It depends on your patience and the time you have in front of you - 3/ It doesn't work and we wait.
Often (but not always) Angular fixes your problem with the next update.
Anyway, it's not worth waiting indefinitely, we will have to find a solution.
Or we end up with AngularJS in 2022 and there we are not in trouble.
Our Angular prototype
The ideal is to have an application prototype that contains enough functionality.
You can be pretty sure that the update will work on most of your apps.
Of course it won't spare you to optimize your CI/CD and take care of your tests.
In any case, here is a list of essential features for an application in my opinion.
- Routing
- Lazy Loading
- Bootstrap
- Httpclient
- TransferState
- SSR
- PWAs
- SEO
- Components
- Services
- Observables
- Guidelines
- Paging
- ScrollBox
- Charts
- Authentication (authentication/Route guard/Role guard/Jwt)
- Ngrx
- Reactive form / Temp Driven form
- Form Modal
- Internationalization
- Testing (unit and end-to-end)
The repository that I use for the moment as a prototype is the following.
https://github.com/ganatan/angular-app
So here we go for the update
For the example we will use this method on our angular-starter application.
The package.json file contains the various dependencies of your project.
Dependencies are, in a way, all the libraries that you have decided to use in your project.
They are managed by npm (node package manager) the Node.js dependency manager.
Regarding the dependencies and their version the npm documentation is as follows
https://docs.npmjs.com/files/package.json#dependencies
There are many version specifiers.
We can use for example
- version Must match version exactly
- ~version "Approximately equivalent to version"
- ^version “Compatible with version”
We will opt for the first " version " specifier, which is the simplest, the most explicit but also the most restrictive.
We will update the package.json file with the latest dependencies
- To check the dependencies to update run the command
npm outdated
- In some cases all dependencies can be updated except typescript
- Angular 17.0.7 accepts for example TypeScript >= 5.2 and <5.3.0
You can check it after the update by running the npm run build script
- So in the case of Angular 17.0.7 all dependencies can be set except typescript.
- Delete package-lock.json file and node_modules directory
Edit the package.json file as follows then run the script
npm install
"dependencies": {
"@angular/animations": "18.0.2",
"@angular/common": "18.0.2",
"@angular/compiler": "18.0.2",
"@angular/core": "18.0.2",
"@angular/forms": "18.0.2",
"@angular/platform-browser": "18.0.2",
"@angular/platform-browser-dynamic": "18.0.2",
"@angular/router": "18.0.2",
"rxjs": "7.8.1",
"tslib": "2.6.3",
"zone.js": "0.14.7"
},
"devDependencies": {
"@angular-devkit/build-angular": "18.0.3",
"@angular/cli": "18.0.3",
"@angular/compiler-cli": "18.0.2",
"@types/jasmine": "5.1.4",
"jasmine-core": "5.1.2",
"karma": "6.4.3",
"karma-chrome-launcher": "3.2.0",
"karma-coverage": "2.2.1",
"karma-jasmine": "5.1.0",
"karma-jasmine-html-reporter": "2.1.0",
"typescript": "5.4.5"
}
It is then sufficient to test all the scripts to verify that the updates have worked.
Testing and deployment
Development has entered its industrialization phase.
Like other industries, quality and quantity must be there.
Agile methods have been invented for this.
Testing is an integral part of this.
We will see that the designers of Angular have planned everything.
Finally we will deploy our application via several methods.
Tests: The secret of my success
Creating a web application is like creating any object.
We create a car, a television or an airplane for example.
And before giving it to someone we will test its operation.
Computer scientists said to themselves that it should be simple and automatic.
As always, it's easier said than done.
A bit of history before we start
Since these beginnings the computer world has sought to improve.
Several working methods have been adopted.
By simplifying we could say that we are there
V-Cycle method versus Agile method.
Is the fastest really what we think it is?
But who did what?
If you want to work in programming for sure you will have to be agile .
The most commonly used Agile method today is the Scrum method .
Below is a brief history of the last twenty years.
In November 2009 Mike Cohn described the test pyramid in his book
Succeeding with Agile: Software Development Using Scrum
With Angular we will focus on one category.
- Unit tests
Let's do an image overview of Angular's architecture to visualize the tests.
Testing with Angular
Without going into details, Angular simplifies our life with the following tools.
Unit tests use
- Karma
- Jasmine
End-to-end tests used
- Protractor
Note: Since Angular 12 end-to-end testing has been disabled.
The Angular documentation concerning the notion of coverage is accessible at this address https://angular.io/guide/testing-code-coverage
I add in package.json an additional script to test the coverage
" coverage ": "ng test --no-watch --code-coverage",
To launch them, we use the corresponding scripts contained in the Package.json file.
# Tests unitaires
npm run test
# Tests unitaires avec couverture
npm run coverage
Update and check
Let's perform the simple modification and debugging test and the source code control test.
- Debugging .
Any modification leads to a recompilation of the code.
For example Edit the app.component.html file
<p>Congratulations and Modifications! Your app is running. 🎉</p>
The compilation is then executed automatically and the browser refreshes.
Noticed :
The favicon.ico file represents your application icon. you can customize it.
In this example you can retrieve the one from this repository.
# Executer
npm run start
# Tester
http://localhost:4200/
# Effectuer des modifications
Code check
As a computer scientist we will try to simplify our lives.
Might as well have some help writing our code.
One of the tools used is linting which improves the quality of the code.
Angular used the TSLint tool accessible at this address https://palantir.github.io/tslint/
Noticed
This command has been disabled starting with Angular 12.
We are waiting for the next tool recommended by angular (probably ESLint?).
As the Google team has not decided, we will integrate ESLint into our project.
For this we will use Schematics which is an Angular code generator based on basic templates.
The ng lint command performs static analysis of TypeScript source code.
# Installation via schematics
ng add @angular-eslint/schematics
# Répondre oui à la question
The package @angular-eslint/schematics@next will be installed and executed.
# Test du code source
npm run lint
Schematics added a script to the package.json (lint) file
and created a .eslint.config.js file
To check that our linter is working
Let's add specific rules to the .eslint.config.js file
Note change this property
- "no-var": " error "
an error will be reported on the use of var - "no-var": " off "
No errors will be reported on the use of var
To check the behavior of the linter.
Let's modify a file for example app.component.ts
And let's write code that doesn't match the rules
We test with the npm run lint script which will give an error
Unexpected var, use let or const instead no-var
"rules": {
"@angular-eslint/directive-selector": [
"error",
{
"type": "attribute",
"prefix": "app",
"style": "camelCase"
}
],
"@angular-eslint/component-selector": [
"error",
{
"type": "element",
"prefix": "app",
"style": "kebab-case"
}
],
"no-undefined": "error",
"no-var": "error",
"prefer-const": "error",
"func-names": "error",
"id-length": "error",
"newline-before-return": "error",
"space-before-blocks": "error",
"no-alert": "error"
}
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule, RouterOutlet],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent {
title = 'angular-starter';
checkError() {
var err = 10;
return err;
}
}
environment
The Angular team has decided to no longer automatically integrate environment settings.
Newer developers who were less concerned with configuration issues did not use these settings.
The Angular documentation is accessible at this address
https://angular.dev/tools/cli/environments#configure-environment-specific-defaults
The command is as follows ng generate environments
The elements necessary for its operation are created automatically.
- Creating a src/environments directory
- Creating an environment.development.ts file
- Creating a file an environment.ts file
- Editing the angular.json file
export const environment = {};
export const environment = {};
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kb",
"maximumError": "1mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kb",
"maximumError": "4kb"
}
],
"outputHashing": "all"
},
"development": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true,
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.development.ts"
}
]
}
},
Deployment
Everything we've done is nice.
But a web application is only of interest if we make it accessible on the web.
This is called deployment .
We are going to see how to do it via two methods from the simplest to the most complicated.
But first, let's talk about compiling .
As we saw earlier the package.json file contains a number of scripts (or commands).
The script we are interested in is npm run build
It allows us to compile our application.
This script executes the command from Angular CLI
ng Build
Without going into details here is how it works.
Via this command Angular uses the Webpack tool (a bundler module) to create the final product.
Running this command will create a dist directory.
This will contain what can be called the final product (or deliverable or artefact).
It is this part that we are going to deploy.
The advice given by Angular is at the following address
https://angular.io/guide/deployment
Deployment with lite-server
The simplest deployment is to use the Http server developed by John Papa.
How to proceed ?
- We install the lite-server library globally with npm
- We run the application in production mode
# Compilation du projet
# !!!!!!!! Très important à ne pas oublier
npm run build
# Installation du serveur de développement lite-server
npm install -g lite-server
# Exécution de notre application
lite-server --baseDir="dist/angular-starter/browser"
# Tester l'application dans notre navigateur avec l'url suivante
http://localhost:3000/
Deployment with nginx
A more complex solution but closer to reality.
We will need to have a virtual server or VPS (Virtual private server).
I advise you to buy one from a VPS provider.
For example OVH or Digital Ocean are among the cheapest and most effective.
On our server (example of a server with ubuntu and the ip address 192.168.100.1)
- Install nginx
- Test nginx
- Copy our dist directory to /var/www/html
- Test the server
# installation de nginx sur le serveur
sudo apt-get --yes install nginx
sudo apt-get update
# Démarre le service nginx
sudo service nginx start
# Tester l'installation du serveur nginx
http://localhost:192.168.100.1/
# Copier le contenu du répertoire dist/angular-starter
# sur le serveur dans le répertoire /var/www/html/
# Tester l'application
http://localhost:192.168.100.1/
Setting up nginx
I add two files that will be useful to you
- an example of an nginx.conf configuration file
- an example of a javascript server.js file to launch your application locally
For use with node server.js command
The script is to be added in package.json
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;
events {
worker_connections 768;
}
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
include /etc/nginx/mime.types;
default_type application/octet-stream;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
ssl_prefer_server_ciphers on;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
gzip on;
include /etc/nginx/conf.d/*.conf;
server {
listen 80 default_server;
listen [::]:80 default_server;
root /var/www/html;
index index.html index.htm index.nginx-debian.html;
server_name _;
location / {
try_files $uri $uri/ =404;
}
}
}
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'dist/angular-starter/browser')));
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'dist/angular-starter/browser', 'index.html'));
});
const port = 4000;
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
Source Code
This guide allowed us to create a web application ready to work.
To simplify your task, you can directly use the source code of this application, to test it and verify that it works.
To do this, simply use the Git software.
I'll show you how.
This first application nevertheless remains basic.
I will suggest a number of steps to complete that will allow you to create a more complex application.
Use Git with source code
En suivant chacun des conseils que je vous ai donnés dans ce guide vous obtenez au final un code source Angular.
Ce code représente votre travail et doit faire l'objet de toute votre attention.
As we saw previously, Git will allow us to manage all our source codes.
A quick tour of Wikipedia https://en.wikipedia.org/wiki/GitHub tells us that
GitHub is the largest source code host in the world.
In June 2022 we count
- 83 million users
- Over 200 million repositories
I therefore advise you to publish your sources on this host.
The source code for this tutorial is of course available on GitHub.
Use git to grab this code and verify that it works.
Just go to the following address
https://github.com/ganatan/angular-react-starter
If you liked this guide and you go to GitHub to check out the code, feel free to hit STAR.
Otherwise, to go even faster, follow the following advice.
Use the classic prompt command under windows (cmd) or linux.
Then type the list of commands
# Create a demo directory (the name is arbitrary here)
mkdir demo
# Go to this directory
cd demo
# Get the source code on your workstation
git clone https://github.com/ganatan/angular-react-starter.git
# Go to the directory that was created
cd angular-react-starter
cd angular
# Run the installation of dependencies (or libraries)
npm install
# Run the program
npm run start
# Check how it works by running the command in your browser
http://localhost:4200/
For further
This tutorial allowed us to create our first application.
This remains relatively simple.
If you want to create a more comprehensive application, you will need to implement some additional principles and features like
- Routing (management of several pages)
- Lazy loading (speed of the application)
- PWAs (operating on mobile and desktop)
- Server Side Rendering (allow SEO)
The next step is logically Routing management.
It requires a complete tutorial which is at the following address
The following steps will get you a prototype application.
- Step 3: Lazy loading with Angular
- Step 4: Bootstrap with Angular
- Step 5: Modules with Angular
- Step 6: Server Side Rendering with Angular
- Step 7: Progressive Web App with Angular
- Step 8: Search Engine Optimization with Angular
- Step 9: HttpClient with Angular
This last step provides an example of an application
The source code of this final application is available on GitHub
https://github.com/ganatan/angular-app