Prima della versione 17, i progetti Angular utilizzavano un approccio a moduli (ngModule), argomento che non sarà trattato in questo corso dato che è stato rimpiazzato da un approccio totalmente basato sui components, chiamato Standalone.
Quindi, nelle versioni precedenti, Angular CLI creava di default un progetto a moduli.
In Angular 17 e 18, utilizzati in questo video corso per la maggior parte dei video, era nesssario specificare l'opzione --standalone nel caso si volesse creare un progetto, per l'appunto, Standalone. Al contrario, senza specificarlo, il progetto sarebbe stato creato con i moduli.
Quindi in questo corso ho usato spesso l'opzione --standalone, come descritto in precedenza.
Tuttavia, da Angular 19 è diventata la configurazione di default e non è più necessario specificarlo in fase di creazione:
Alternativa con '@angular/create'
È disponibile un "nuovo" modulo npm (da Angular v.14) per la creazione di progetti Angular senza la necessità di utilizzare la CLI globale: @angular/create
È ancora poco utilizzato / documentato e ammetto che anch'io finora non l'ho ancora utilizzato.
La sintassi per creare un nuovo progetto è:
param1 e param2 rappresentano gli stessi parametri disponibili per il comando new della CLI.
Come abbiamo visto, è possibile creare facilmente un progetto Angular eseguendo npx dal terminale:
terminal
Questo comando effettua il download dell'ultima versione di Angular CLI .
Il vantaggio di questo approccio è che utilizzeremo sempre l'ultima versione di Angular ogni qualvolta creeremo un nuovo progetto.
npm vs npx
In alternativa avremmo potuto installare globalmente il pacchetto Angular CLI, utilizzando l'opzione -g (ovvero global) affinché sia disponibile in qualunque directory:
terminal
Quindi ci possiamo posizionare in una qualunque cartella del nostro disco e creare un nuovo progetto con il comando ng:
terminal
Tuttavia, nel momento in cui si ha la necessità di creare un progetto con l'ultima versione del framework, dovremo aggiornare localmente @angular/cli con una nuova installazione.
Analizziamo più in dettaglio i parametri di questo comando:
terminal
In sintesi, npx scarica ed esegue l'ultima versione di Angular CLI per creare un nuovo progetto Angular con stili inline, modelli inline e saltando la creazione di test.
npx: utility da riga di comando che viene fornita da npm (Node Package Manager) ed è usata per scaricare ed eseguire pacchetti.
-p @angular/cli: l'opzione -p viene usata con il comando npx per specificare il pacchetto da eseguire.
ng new [PROJECT_NAME]: ng new è un comando di Angular CLI che permette di creare un nuovo progetto.
-s -t -S: questi sono i flag usati per personalizzare la configurazione del progetto Angular:
-s: genera componenti che usano CSS in linea (invece di un file .css esterno. Ne parleremo nel prossimo capitolo dedicato al CSS)
-t: il template HTML è incluso direttamente nel file TypeScript, come stringa, invece di un file .html separato
-S: evita di generare gli unit test
Queste impostazioni saranno quelle di default nel momento in cui genereremo nuovi componenti sfruttando sempre la CLI di Angular ed eventualmente si possono cambiare modificando il file angular.json.
Che cos'è Node Version Manager (NVM)?
Posso affermare di non aver mai installato NodeJS dal sito ufficiale perchè solitamaente utilizzo NVM.
NVM (linux - Window ) consente agli sviluppatori di installare e passare facilmente tra diverse versioni di Node.js sulla stessa macchina, eliminando la necessità di disinstallazioni e reinstallazioni manuali, risparmiando tempo ed evitando conflitti di versione.
Quando può essere utile?
Per esempio potrebbe essere necessario utilizzare Node v.12 per eseguire un vecchio progetto Angular e Node v.20 per un progetto React o Next.
Di seguito alcuni dettagli aggiuntivi in lingua inglese, che ho ricopiato da un altro mio libro online su Angular e che penso possano esservi comunque utili:
More details about the installation process
After starting the installation process you will first be asked which CSS format to use between CSS, Sass and Less.
Select CSS.
Anyway feel free to select Sass or Less in your future projects.
Then you will be asked whether to use client side rendering or server side rendering.
Select Client Side:
Client vs Server Side Rendering
SSR (Server-Side Rendering) generates HTML on the server, sending a fully-rendered page to the client. This results in faster initial load times and better SEO, as search engines can index content more easily.
This can be especially useful for public websites such as landing pages, e-commerce and so on...
CSR (Client-Side Rendering) relies on JavaScript to build the HTML in the browser. The initial load might be slower, but subsequent interactions are faster and more dynamic. CSR is common in single-page applications (SPAs), providing a smoother user experience after the initial load.
When you create a new Angular project with the CLI (ng new project-name) using the parameters I have described in the previous recipe, several files and directories are generated in the root of your project.
Here's a breakdown of the key files and their purposes:
angular.json: defines project settings, build options, file paths, and more.
package.json: lists the npm packages required for your project and scripts for running, building, and testing your application
package-lock.json: ensures that the same versions of dependencies are installed every time the project is set up, providing consistency across different environments.
tsconfig.json: specifies the root files and compiler options required to compile the project. Helps TypeScript understand how to compile the code.
tsconfig.app.json: extends tsconfig.json with settings specific to the app's source files, excluding tests.
tsconfig.spec.json: extends tsconfig.json with settings specific to unit tests, ensuring they are compiled correctly.
.editorconfig: helps maintain consistent coding styles across different editors and IDEs.
.gitignore: ensures that specific files and folders (like node_modules) are not tracked by version control
README.md: contains information about your project, such as how to run, build, and test the application.
src/: The main directory where all your application code resides.
node_modules/: contains all the installed npm packages and it's populated when you run npm install and includes all dependencies listed in the package.json
angular.json
The angular.json file defines project settings, build options, file paths, and more.
It also helps manage configurations for different environments and build targets.
But that’s not all. Remember when we used the -t -s -S options at the beginning of the chapter?
These choices are saved in this file and you can change them at any time
A component is a fundamental building block of an Angular application.
In short, it manages a portion of the layout and its logic.
A component combines HTML, CSS, and TypeScript to define a piece of the user interface.
Components make development efficient by promoting reusability, maintainability, and modularity, allowing developers to build complex User Interfaces (UI).
The app-root component is the main, or root, component of an Angular application. It acts as the entry point for the application, where the initial rendering and bootstrap process begins.
src/
app.component.ts
When you create a new Angular project using the Angular CLI, the app-root component is generated by default, serving as the parent container for the entire application.
How to define a component in Angular:
The @Component decorator is applied on the AppComponent class and it configures the component with the required properties, that are called metadata
selector: 'app-root', which means this component can be utilised in HTML using the <app-root></app-root> tag.
<Practice>
Change the Hello Angular text to display I love Angular instead. Try it in the playground below.
Switch between "Editor | Preview | Both" using the tabbar in the footer
When you create an Angular project using Angular CLI, other two files are created and located close to app.component.ts:
src/
app.component.ts
app.config.ts
app.routes.ts
app.routes.ts and app.config.ts are two important configuration files typically found in the /src directory. They play crucial roles in setting up the application's routing and configuration:
app.routes.ts is used to define the routing configuration for the Angular application. Routing allows you to navigate between different views or components based on the URL.
app.config.ts is used to centralize configuration settings for the Angular application. This can include settings for services, environment variables, or other global configurations.
We'll talk about these topics in the next chapters
Angular CLI vs StackBlitz
In real projects you will use Angular CLI or tool like NX to generate a new project but in the next lessons we will use a code playground instead, Stackblitz , which allows us to have an online editor and experiment without the need to create a new project each time.
You can therefore decide to study and try directly from this site or create a project and work on it in parallel.
In any case, if you use StackBlitz we suggest you create an account so you can save (fork) all the exercises in your StackBlitz profile