Home Programming Angular Design Patterns and Best Practices

Angular Design Patterns and Best Practices

By Alvaro Camillo Neto
books-svg-icon Book
eBook $35.99
Print $44.99
Subscription $15.99
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $35.99
Print $44.99
Subscription $15.99
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Chapter 1: Starting Projects the Right Way
About this book
Single page applications (SPAs) have become the standard for most web experiences. Angular, with its batteries-included approach, has emerged as a powerful framework for simplifying the development of these interfaces by offering a comprehensive toolbox. This book guides you through the Angular ecosystem, uncovering invaluable design patterns and harnessing its essential features. The book begins by laying a strong foundation, helping you understand when and why Angular should be your web development framework of choice. The next set of chapters will help you gain expertise in component design and architecting efficient, flexible, and high-performing communication patterns between components. You’ll then delve into Angular's advanced features to create forms in a productive and secure way with robust data model typing. You'll also learn how to enhance productivity using interceptors to reuse code for common functionalities, such as token management, across various apps. The book also covers micro frontend architecture in depth to effectively apply this architectural approach and concludes by helping you master the art of crafting tests and handling errors effortlessly. By the end of this book, you'll have unlocked the full potential of the Angular framework.
Publication date:
February 2024
Publisher
Packt
Pages
270
ISBN
9781837631971

 

Starting Projects the Right Way

Angular is a framework that has the motto “batteries included” as a development philosophy. This means that practically all the resources you need for your frontend application needs are already available as soon as you create a new project.

In this chapter, you will understand why choose Angular for your web application, what its main characteristics and design are, and why companies, especially the biggest ones, choose Angular as the main framework for developing single-page applications.

You will explore the technologies that make up the framework and thus take greater advantage of possible alternatives if you need them for a specific case. You’ll also set up your workspace with the best tools to help you and your team’s productivity.

In this chapter, we’re going to cover the following topics:

  • Why choose Angular?
  • What technologies are present in the ecosystem?
  • Configuring your development environment
  • Starting an Angular project
  • Using the Angular Command-Line Interface (CLI) for your productivity

By the end of this chapter, you will have arguments for using Angular in your project and be more productive in your development workspace.

 

Technical requirements

To follow the instructions in this chapter, you’ll need the following:

The code files for this chapter are available at .

 

Why choose Angular?

The choice of technology to be used in a given project is critical to its success. You, as a project developer or architect, must help your team in this mission by choosing the best tool for the job.

The Angular framework is one of the most used tools for building a single-page application, along with React and Vue. When choosing the right tool for the job, you need to answer why.

The following are some arguments for choosing Angular.

Batteries included

Angular is an opinionated framework, which means that the Angular development team has already made several choices of tools and solutions for every challenge that a web application can have. This way, you and your team don’t have to research which route engine or state management library you should use; it’s all included and configured for your project.

This feature also simplifies the onboarding of new developers in your team. Following the guidelines proposed by the documentation and using the best practices, Angular projects usually have the same structure and method of development. Knowing Angular you can quickly locate yourself in any ongoing project.

Google support

Angular was created and maintained by the Angular team at Google. Although excellent frameworks such as Vue.js and Svelte are maintained only by their communities, having such a big tech company supporting the framework brings security to the choice of technology, especially for large companies.

In addition, Angular is used in more than 300 internal applications and Google products, which means stability and quality because, before each new version of the framework is released, it is validated in all these applications.

The Angular team has strived since version 13 to increase transparency within the community by releasing a roadmap (https://angular.io/guide/roadmap) detailing all the improvements in progress and what to expect for the future of the framework, giving you peace of mind that it will be supported for years to come.

Community

Technology is only as alive as the community that supports it, and Angular has a huge one. Meetups, podcasts, events, articles, and videos – the Angular community has many resources to help developers.

The people who make up this community also have the important contribution of giving feedback, creating and correcting issues in Angular. As it is an open source project, everyone is invited to evaluate and contribute to the code.

The Angular team also asks the community for help with major framework decisions through Requests for Comment (RFCs).

In addition, the community creates many libraries that expand the possibilities of the framework, such as NgRx (https://ngrx.io/) for advanced state management and Transloco (https://ngneat.github.io/transloco/) to support internationalization, among others.

Tooling

One of the differentiating factors of Angular compared to its competitors is the focus from the beginning on tooling and developer experience. The Angular CLI tool is a powerful productivity tool that we will explore in this chapter, which is used far beyond the simple creation and setup of a project.

From a testing point of view, Angular is already equipped and configured with Karma as a test runner and Jasmine as a configuration tool. Angular’s tooling already configures the project build using webpack and already has a dev server.

The tool is also extensible, allowing the community to create routines for configuring and updating their libraries.

With these arguments, you will be able to base your choice of Angular on your project; let’s see now which technologies make up the framework’s ecosystem.

 

What technologies are present in the ecosystem?

The Angular team, when creating the solution for the growing complexity of web application development, decided to unite the best tools and libraries in an opinionated package with the maximum number of configurations made by default.

We then have the following libraries that make up the core of Angular.

TypeScript

TypeScript is a superset of the JavaScript language that adds type checking and other features to the language, ensuring a better developer experience and security for web development.

It has been present in Angular since its first version and is the cornerstone of the framework that enables several features such as dependency injection, typed forms and Angular’s tooling.

TypeScript is currently the preferred tool for backend development in Node.js and is encouraged by communities of other frameworks such as React and Vue.js.

RXJS

RXJS is a library that implements the reactive paradigm (https://www.reactivemanifesto.org/) in the JavaScript language.

Since the first version of Angular, reactivity was a core theme that the framework wanted to achieve and so it uses the RXJS library to help with it.

HTTP requests, routes, forms, and other Angular elements use the concepts of observables and their operators to provide Angular developers with the tools to create more fluid and dynamic applications with less boilerplate code.

RXJS also provides mechanisms for state management in a frontend application without the need to use more complex patterns such as Redux.

Karma and Jasmine

Quality should be the top priority in any application and this is especially important in frontend applications as for the user, it is the application.

One of the ways to attest to quality is through testing, and with that in mind, Angular already comes by default with the tool duo of Jasmine and Karma.

Jasmine is a framework for unit-testing JavaScript and TypeScript applications with several functions for assertion and test assembly.

Karma is the test runner, that is, the environment where the unit test setup is executed with the help of Jasmine. This environment, configured in its configuration file, runs in browsers, making the test more realistic in comparison to customers’ daily lives.

Many people in the community switch these tools for the Jest framework due to performance in the execution of the tests, which is totally fine and even facilitated by the Angular CLI; however, it should be noted that this tool does not run in a browser, which really improves the performance of the test execution but may hide some particularity that only testing in a browser would provide.

Webpack

After the development of an application, it is necessary to create the bundle to send it to production, and Webpack is the tool that the Angular team chose for this task.

Webpack is a very powerful and versatile bundler, and it is thanks to it that the framework manages to make some interesting optimizations such as tree shaking and lazy loading of bundles.

However, Webpack is complex in its configuration, and with that in mind, the Angular team has already set up and created some abstractions for fine-tuning the tool, such as the angular.json file.

We understand what pieces make up the framework and how they relate to delivering rich and fluid interfaces. We will now set up our development environment.

 

Configuring your development environment

A well-organized environment with the right tools is the first step toward excellence and productivity; now, let’s set this environment up in your workspace.

After installing Node.js following the instructions in the Technical requirements section, the following tools and their plugins will help you in your workflow.

VS Code

VS Code (https://code.visualstudio.com/) is currently the default tool for most developers, especially for frontend projects.

There are other very good ones such as WebStorm (https://www.jetbrains.com/webstorm), but VS Code, with its plugins especially for Angular projects, facilitates great productivity and ergonomics.

To install the plugins listed here, in the code editor, click on Extensions or use the shortcut Ctrl + Shift + X (Windows) or Cmd + Shift + X (macOS).

The following are the VS Code plugins recommended for developing Angular applications.

Git Extension Pack

Git Extension Pack (https://marketplace.visualstudio.com/items?itemName=donjayamanne.git-extension-pack) is not specifically for developing Angular applications but it is useful for any kind of work.

Git is the default tool for version control and VS Code has native support for it. This set of plugins improves this support even further, adding the ability to read comments and changes made in previous commits in the editor, support for multiple projects, and a better view of your repository history and logs.

Angular Language Service

The Angular Language Service (https://marketplace.visualstudio.com/items?itemName=Angular.ng-template) extension is maintained by the Angular team and adds support for most of the framework’s functionality right from the code editor.

By adding this extension to your editor, it will have the following features:

  • Autocomplete in the HTML template file, allowing you to use component methods without having to consult the TypeScript file
  • Checking for possible compilation errors in HTML template files and TypeScript files
  • Quick navigation between HTML and TypeScript templates, allowing you to consult the definition of methods and objects

This extension is also available for other IDEs such as WebStorm and Eclipse.

Prettier

Prettier (https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) is a JavaScript tool that solves the code formatting problem. It is opinionated on formatting settings although some customization is possible.

In addition to TypeScript, Prettier formats HTML, CSS, JSON, and JavaScript files, making this extension useful also for backend development using Node.js.

To standardize formatting across your entire team, you can install Prettier as a package for your project and run it on the project’s CI/CD track, which we’ll see in Chapter 12, Packaging Everything – Best Practices for Deployment.

ESLint

When creating an application, the use of a linter is highly recommended to ensure good language practices and avoid errors from the beginning of development.

In the past, the default tool for linting TypeScript projects was TSLint, but the project has been absorbed by ESLint (https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint), which allows you to verify JavaScript and TypeScript projects.

With this extension, verification occurs quickly while you type the code of your project. ESLint can be installed as a package in your Angular project and thus performs this validation on the CI/CD conveyor of your project, which we will see in Chapter 12, Packaging Everything – Best Practices for Deployment.

EditorConfig

The EditorConfig (https://marketplace.visualstudio.com/items?itemName=EditorConfig.EditorConfig) plugin has the function of creating a default configuration file for not only VS Code but also any IDE that supports this format.

This plugin is useful for standardizing things for your project and your team – for example, the number of spaces that each Tab key represents, or whether your project will use single quotes or double quotes to represent strings.

To use it, just create or have a file named .editorconfig at the root of your project and VS Code will respect the settings described in the file.

VS Code settings

VS Code, in addition to extensions, has several native settings that can help in your day-to-day work. By accessing the File menu, we can activate the automatic saving flag so you don’t have to worry about pressing Ctrl + S all the time (although this habit is already engraved in stone in our brains...).

Another interesting setting is Zen mode, where all windows and menus are hidden so you can just focus on your code. To activate it, go to View | Appearance | Zen Mode, or use the keyboard shortcut Ctrl + K + Z for Windows/Linux systems and Cmd + K + Z for macOS.

To improve the readability of your code during editing, an interesting setting is Bracket coloring, which will give each parenthesis and bracket in your code a different color.

To enable this setting, open the configuration file using the shortcut Ctrl + Shift + P for Windows/Linux or Cmd + Shift + P for macOS and type Open User Settings (JSON).

In the file, add the following elements:

{
  "editor.bracketPairColorization.enabled": true,
  "editor.guides.bracketPairs": true
}

VS Code also has the Inlay Hints feature, which shows details of parameter types and return methods, as well as other useful information on the line you are reading in the code.

To configure it in the Settings menu, look for Inlay Hints and activate it if it is not already configured. For the development of your Angular application, you can also perform specific configurations by selecting TypeScript.

It is also possible to turn on this functionality by directly configuring the settings.json file with the following elements:

{
  "typescript.inlayHints.parameterNames.enabled": "all",
  "typescript.inlayHints.functionLikeReturnTypes.enabled": true,
  "typescript.inlayHints.parameterTypes.enabled": true,
  "typescript.inlayHints.propertyDeclarationTypes.enabled": true,
  "typescript.inlayHints.variableTypes.enabled": true,
  "editor.inlayHints.enabled": "on"
}

Fira Code font and ligatures

An important detail that not every developer pays attention to is the type of font they use in their code editor. A confusing font can make it difficult to read code and tire your eyes.

The ideal option is to use monospaced fonts, that is, fonts where the characters occupy the same horizontal space.

A very popular font is Fira Code (https://github.com/tonsky/FiraCode), which, in addition to being monospaced, has ligatures for programming – that is, joining or changing characters that represent symbols such as ==, >=, and =>, as shown in the following figure:

Figure 1.1 – Example of symbols with font ligatures

Figure 1.1 – Example of symbols with font ligatures

After installing the font on your operating system, to enable ligatures in the font in VS Code, access the configuration file as in the previous section and add the following elements:

{
  "editor.fontFamily": "Fira Code",
  "editor.fontLigatures": true,
}

Standardizing the extensions and settings in the project

In the Why choose Angular? section, we learned that one of the advantages of choosing this framework for your project is the standardization it provides to development and the team.

You can also standardize your VS Code settings and record them in your Git repository so that not only you but also our team can have that leap in productivity.

To do this, in your repository, create a folder called .vscode, and inside that folder, create two files. The extensions.json file will have all the extensions recommended by the project. In this example, we will use the extensions we saw earlier:

{
  "recommendations": [
    "dbaeumer.vscode-eslint",
    "esbenp.prettier-vscode",
    "Angular.ng-template",
    "donjayamanne.git-extension-pack",
    "editorconfig.editorconfig"
  ]
 }

Let’s also create the settings.json file, which allows you to add VS Code settings to your workspace. These settings take precedence over user settings and VS Code’s default settings.

This file will have the previously suggested settings:

{
  "editor.bracketPairColorization.enabled": true,
  "editor.guides.bracketPairs": true
  "editor.fontFamily": "Fira Code",
  "editor.fontLigatures": true,
  "typescript.inlayHints.parameterNames.enabled": "all",
  "typescript.inlayHints.functionLikeReturnTypes.enabled": true,
  "typescript.inlayHints.parameterTypes.enabled": true,
  "typescript.inlayHints.propertyDeclarationTypes.enabled": true,
  "typescript.inlayHints.variableTypes.enabled": true,
  "editor.inlayHints.enabled": "on"
}

By synchronizing these files in your repository, when your team members download the project and open VS Code for the first time, the following message will appear:

Figure 1.2 – VS Code prompt for recommended extensions

Figure 1.2 – VS Code prompt for recommended extensions

Once confirmed, all the extensions configured in the file will be installed in the VS Code development environment of your team members, thus automating the task of standardizing the team’s work environment.

Angular DevTools

One tool missing from the Angular framework was a way to drill down into an application in the browser. Browsers such as Chrome and Firefox have greatly improved the developer experience over the years, broadly for all types of websites.

With that in mind, the Angular team, starting from version 12, created the Angular DevTools extension for Chrome and Firefox.

To install it, you need to go to the extension store of the browser (Chrome or Firefox) and click on Install.

With it installed, access to the site built with Angular, and with the build set up for development, the Angular tab will appear in the developer tools:

Figure 1.3 – Angular DevTools Chrome extension example

Figure 1.3 – Angular DevTools Chrome extension example

This tool allows you to browse the structure of your app, locate the code of the components on the screen, and profile your application to detect possible performance problems.

Now you have a productive development environment for developing Angular applications, we are ready to start our application.

 

Starting an Angular project

We have our tools installed and configured and now we are going to start our Angular application. First, we are going to install the Angular CLI, which will be responsible for creating and building our application. In your terminal, type the following command:

npm install -g @angular/cli@16

After installing the CLI, use the following command to confirm the installation:

ng version

The following figure should appear in your terminal (the Angular version may be newer):

Figure 1.4 – Angular CLI prompt confirming you have correctly installed the tool

Figure 1.4 – Angular CLI prompt confirming you have correctly installed the tool

If the ng command is not recognized, restart the terminal. This ng command is the CLI call and will be used in this and other chapters of the book.

Let’s start our project using the ng new command. The Angular CLI will ask for some definitions of your project:

  1. The first is the name of the project; for this example, enter angular-start.
  2. The second prompt is whether you’d like to configure your project’s routing, for which we’ll input Yes. This request will tell the CLI to create the base files for the route, which is recommended for most applications; an exception could be an Angular library you would like to create.
  3. The next prompt will tell you which CSS format your project will use. Angular by default supports conventional CSS and the SCSS, Sass, and Less tools. For this and other examples in the book, we will use CSS.
  4. Confirming the Angular CLI will create the entire initial structure of the project and will install the dependencies using the npm i command, leaving everything ready for the start of development, as in the following example.
Figure 1.5 – Prompt of files generated by angular-cli

Figure 1.5 – Prompt of files generated by angular-cli

To verify that the project was successfully installed, in your operating system’s terminal, type the following command:

ng serve

This command will start the development web server and load the example project page, as shown in Figure 1.6:

Figure 1.6 – Example page generated by angular-cli on project creation

Figure 1.6 – Example page generated by angular-cli on project creation

The ng new command has other options that can be used for specific needs in your project. They are listed in the official documentation (https://angular.io/cli/new), and here are some that may be interesting:

  • Parameter '—package-manager': With this parameter, it is possible to choose another node package manager such as yarn (https://yarnpkg.com/).
  • Parameter '--skip-install': With this parameter, the CLI does not perform the package installation step, which can be useful for creating automation tools for your team.
  • Parameter '--strict': This parameter is set to true by default, but it is important to mention it because it configures your project in strict mode, which configures the TypeScript and Angular mechanisms to improve type and template validations. For more details, see Chapter 3, TypeScript Patterns for Angular.

Project structure

The Angular CLI creates the project in the structure recommended by the Angular team with all files configured by default. To deepen our knowledge of the framework, we need to know the main files, their functions, and available customizations as follows:

  • src: This is the folder where your project will be, including all components, modules, and services.
  • assets: Contains the static files you will need in your project, such as images and icons. In the build process, by default, it will export the files from this folder without any changes to the production build.
  • index.html: This is the initial file of your application. This file will be used in the build process, and it is recommended not to change it unless there is a very specific need. The title information must be changed with an Angular feature and not directly in this file.
  • main.ts: This is the first JavaScript file that will be loaded in your application. You shouldn’t change it unless your project has a very specific need for it to be changed.
  • styles.css: This is the file that can contain the global CSS of your application, that is, the CSS that can be read by all components since Angular by default isolates the CSS of each component. This file is usually modified when your project uses a design system such as Material (https://material.angular.io/).
  • .editorconfig: As described in the VS Code section of this chapter, this file, together with the extension that interprets and configures the IDE, allows standardization in your code conventions, such as the use of double or single quotes and the use of tabs or indentation spaces.
  • angular.json: This is the most important configuration file for an Angular application. In it, you can customize the way your project is built, and define budgets for the size of bundles (more details in Chapter 12, Packaging Everything – Best Practices for Deployment), among other settings.
  • package.json and package-lock.json: These files refer to the dependencies of the npm packages of your project and also the place to create the npm scripts that will be used in the creation of the CI/CD pipes of the Angular application (more details in Chapter 12, Packaging Everything – Best Practices for Deployment).

As of version 15 of Angular, the CLI hides Karma configuration files and environment variables files (enviroment.ts) by default with the justification of simplifying the project structure. It is still possible to create these files for fine-tuning your application build, test, and environment processes (more details in Chapter 8, Improving Backend Integrations: the Interceptor Pattern).

We created our project using the angular-cli tool, but this tool can help us even more, as we will learn next.

 

Using the Angular CLI for your productivity

We learned how to create a project with all its options, but the Angular CLI is far from being just a project creation tool. It is a very important tool for the productivity and workflow of an Angular application. All available options are described using the following command:

ng --help

We will detail some of the most interesting options here, and in the next chapters, we will continue to use them, given the practicality of this tool.

ng add

This command has the function of adding an Angular library to your project. You might be wondering, Doesn’t npm install do the same thing? and you’d be right. However, when you need to install Angular Material as a library, installing the dependency is just the first step.

Many libraries such as Angular Material itself need the configuration of the angular.json file and the creation of some other lib file, among other tasks. The ng add command allows the library creator to automate these steps and simplify their workflow.

To exemplify this in the project that we created, we will use the following command:

ng add @angular/material

Executing the preceding command, the library will make some prompts (in the same format as we saw for the ng new command) and in the end, it will configure our project with the library, as shown in Figure 1.7.

Figure 1.7 – Installation of Angular Material using angular-cli

Figure 1.7 – Installation of Angular Material using angular-cli

ng update

In the development of our projects, updating the version of something often takes more time than adding a new library. The ng update command makes this task almost trivial, being one of the greatest allies when it comes to updating the Angular version of our application.

On the Angular update website (https://update.angular.io/), the Angular team details how to update a project in old versions. Larger and more complex projects may have their quirks (which are usually described on the website), but all applications start with the following command (in this case, version 15):

ng update @angular/core@15 @angular/cli@15

The Angular CLI will take care of updating the package and even making possible automation-breaking changes; often, only this is enough to completely update your application.

This command, like ng add, is also available for libraries that have been configured by their authors and can benefit from this automation.

ng serve

This command is used by every Angular developer (it’s the first thing you should do after creating a project) and its function is to upload a development web server.

One of the most interesting and productive features of this command is the hot-reload capability; that is, the server restarts every time a project file is updated, allowing you to see its modification in real time in the interface.

A productivity tip for this command is to use the open parameter as follows:

ng serve --open

With this parameter, as soon as Angular loads your application, the CLI will open the default browser of your operating system with the application you are working on.

ng build

The ng build command is intended to prepare your application bundle to be executed by the production web server of your choice.

It performs a series of optimizations to guarantee the delivery of the smallest possible bundle of your application.

This results in a performance gain since with a smaller bundle, your client downloads faster, which is important, especially in environments with slow internet.

We will discuss this command in more detail in Chapter 12, Packaging Everything – Best Practices for Deployment.

ng deploy

The ng deploy command allows you to fully deploy your application to a cloud provider such as Microsoft Azure.

This command works together with the Angular library of the provider you want to use, so for it to work, you need to install it.

We will discuss this command in more detail in Chapter 12, Packaging Everything – Best Practices for Deployment.

ng generate

The ng generate command has the function to generate almost all types of Angular components that your application can use. This function brings a productivity gain in your workflow as it generates all the necessary files.

Let’s generate our about page in our example project with the following command:

ng generate component about

We can analyze in our project folders that the Angular CLI created the TypeScript, HTML, and CSS files necessary for rendering the component.

However, it also generated the unit test file for this component and updated the module for its use. All these files already have the minimum boilerplate for the development of the component.

In addition to generating practically all standard Angular components, this command can be used by external libraries that want to provide this development experience, as in the following example of Angular Material:

ng generate @angular/material:navigation home

In almost every chapter of the book, we’ll use this command to generate the components we’re going to study and the best practices and patterns for them.

 

Summary

In this chapter, we covered the features and philosophy of Angular and how to start a project in the most productive way. We learned which technologies make up its ecosystem and how to configure its desktop with the best VS Code extensions and settings. Finally, we learned how to start a project with the Angular CLI and what other features this powerful tool can provide us with.

Now you’ll be able to argue why to use Angular in your team’s project and you’ll be able to help it set up a productive work environment. You’ll also be able to use the Angular CLI to create and maintain your project.

In the next chapter, we will learn how to organize the components of an Angular application.

About the Author
  • Alvaro Camillo Neto

    Alvaro is a software engineer, speaker and instructor in Brazil. He works in the technology industry for over 10 years dedicated to the development of business solutions in a large company in the industry. Alvaro is a technology enthusiast and sees knowledge sharing as an opportunity to help the community that helped him so much and the best way of learning. He has performed from small meetups to large events focusing on the themes of developing web solutions. He also shares knowledge on his blog and participates in the organization of AngularSP.

    Browse publications by this author
Latest Reviews (1 reviews total)
Angular Design Patterns and Best Practices
Unlock this book and the full library FREE for 7 days
Start now