Reader small image

You're reading from  Learning Angular - Fourth Edition

Product typeBook
Published inFeb 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781803240602
Edition4th Edition
Languages
Tools
Right arrow
Authors (2):
Aristeidis Bampakos
Aristeidis Bampakos
author image
Aristeidis Bampakos

Aristeidis Bampakos is a Web Development Team Lead at Plex-Earth who specializes in the development of web applications with Angular. He has been an Angular Google Developer Expert (GDE) since 2020 and works as an Angular Senior Tech Instructor at Code.Hub, a private educational institute, where he nurtures aspiring Angular developers and professionals. He is also the author of Angular Projects with Packt.
Read more about Aristeidis Bampakos

Pablo Deeleman
Pablo Deeleman
author image
Pablo Deeleman

With sound expertise in front-end libraries and frameworks such as Backbone.js, Knockout.js, VueJS, React, Svelte, AngularJs, and Angular, Pablo Deeleman has developed his career since 1998 as a JavaScript engineer across a broad range of successful companies such as Gameloft, Red Hat or Dynatrace, just to name a few. He currently works as Staff Software Engineer at Twilio, the global leader in customer engagement communications. Pablo Deeleman has contributed to the dev community with several books on Angular since 2016, all published by Packt Publishing.
Read more about Pablo Deeleman

View More author details
Right arrow

Group features into modules

Each Angular module represents a particular feature of an Angular application. The way these feature modules are added to the application depends on the business needs. In this section, we will investigate three different ways:

  • Adding modules in the main application module
  • Adding modules to another feature module
  • Grouping feature modules by type

In the following sections, we will explore each way in more detail.

Add module in the main module

We have already learned how to create a new Angular module for our application using the Angular CLI. Creating an Angular module does not make it automatically available to the application. It is our responsibility to register the new module with the rest of the application using the main application module:

  1. Open the app.module.ts file and add a new import statement to import ProductsModule:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import...

Leveraging Angular built-in modules

We have already learned that the Angular framework contains a rich collection of first-party libraries that can help us during the development of an Angular application. The functionality of each library is exposed through an Angular module. We need to import these modules into our applications to start using their functionality as with any other module in Angular. Below are some of the most widely used modules of the Angular framework:

  • BrowserModule: It is used to run Angular applications into the browser and must be imported only once in an Angular application.
  • CommonModule: It contains specific Angular artifacts that support the Angular template syntax and enrich our HTML templates. We will work most of the time with this module in this book.
  • FormsModule/ReactiveFormsModule: It allows us to build HTML forms for interacting with user input data. We will learn more about Angular Forms in Chapter 10, Collecting User Data with Forms.
  • HttpClientModule...

Summary

Angular modules are an essential part of an Angular application. They define the main features of the application and organize them cohesively and efficiently.

We learned the purpose of a module in an Angular application and how different they are from JavaScript modules. We also explored the structure of an Angular module and how Angular uses decorators to configure it.

We also learned the different ways to add a module in an Angular application and how modules communicate with each other over a public API. Finally, we saw how we could group modules according to their features and what are some of the most widely used Angular built-in modules.

In the next chapter, we will learn more about the functionality that goes into an Angular module and how it can be represented as an Angular component.

Interacting with the template

As we have learned, creating an Angular component using the Angular CLI involves generating a set of accompanying files. One of these files is the component template containing the HTML content displayed on the page. In this section, we will explore how to display and interact with the template through the following topics:

  • Loading the component template
  • Displaying data from the component class
  • Styling the component
  • Getting data from the template

We will start our journey in component template land by exploring how we render the component on the web page.

Loading the component template

We have already learned that Angular uses the selector to load the component in an HTML template. A typical Angular application loads the template of the main component at application startup. The <app-root> tag we saw in Chapter 1, Building Your First Angular Application, is the selector of the main application component...

Component inter-communication

In a nutshell, Angular components expose a public API that allows them to communicate with other components. This API encompasses input properties, which we use to feed the component with data. It also exposes output properties we can bind event listeners to, thereby getting timely information about changes in the state of the component.

Let’s look at how Angular solves the problem of injecting data into and extracting data from components through quick and easy examples in the following sections.

Passing data using an input binding

We will expand our products module and create a new component that will display the details of a product, such as a name and a price. Data representing the specific product details will be dynamically passed from the product list component.

For now, we will only pass and display the name of the product. To follow along with code samples, copy the CSS styles from the styles.css file...

Encapsulating CSS styling

We can define CSS styling within our components to better encapsulate our code and make it more reusable. In the Creating our first component section, we learned how to define CSS styles for a component using an external CSS file through the styleUrls property, or by defining CSS styles inside the TypeScript component file with the styles property.

The usual rules of CSS specificity govern both ways:

https://developer.mozilla.org/docs/Web/CSS/Specificity

CSS management and specificity become a breeze on browsers that support Shadow DOM, thanks to scoped styling. CSS styles apply to the elements contained in the component, but they do not spread beyond their boundaries.

On top of that, Angular embeds style sheets at the head of a document so that they may affect other elements of our application. To prevent this from happening, we can set up different levels of view encapsulation.

View encapsulation...

Deciding on a change detection strategy

Change detection is the mechanism that Angular uses internally to detect changes that occur in component properties and reflect these changes to the view. It is triggered on specific events such as when the user clicks on a button, an asynchronous request is completed, or a setTimeout and setInterval method is executed. Angular monkey patches these event types by overwriting their default behavior, using a library called Zone.js.

Every component has a change detector that detects whether a change has occurred in its properties by comparing the current value of a property with the previous one. If there are differences, it applies the change to the component template. In the product detail component, when the name input property changes as a result of an event that we mentioned earlier, the change detection mechanism runs for this component and updates the template accordingly.

However, there are cases where this behavior...

Introducing the component lifecycle

Lifecycle events are hooks that allow us to jump into specific stages in the lifecycle of a component and apply custom logic. They are optional to use but might be of valuable help if you understand how to use them.

Some hooks are considered best practices, while others help debug and understand what happens in an Angular application. A hook comes with an interface that defines a method we need to implement. The Angular framework ensures the hook is called, provided we have implemented this method in the component.

Defining the interface in the component is not obligatory, but it is considered a good practice. Angular cares only about whether we have implemented the actual method or not.

The most basic lifecycle hooks of an Angular component are:

  • OnInit: This is called when a component is initialized
  • OnDestroy: This is called when a component is destroyed
  • OnChanges: This is called when...

Summary

In this chapter, we explored the structure of Angular components and the different ways to create them. We learned how to create a standalone component or register it with an Angular module. We discussed how to isolate the component’s HTML template in an external file to ease its future maintainability. Also, we saw how to do the same with any style sheet we wanted to bind to the component, in case we did not want to bundle the component styles inline. We also learned how to use the Angular template syntax and interact with the component template. Similarly, we went through how components communicate in a bidirectional way using property and event bindings.

We were guided through the options available in Angular for creating powerful APIs for our components, so that we can provide high levels of interoperability between components, configuring their properties by assigning either static values or managed bindings. We also saw how a component can act as a host component...

Join our community on Discord

Join our community’s Discord space for discussions with the author and other readers:

https://packt.link/LearningAngular4e

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Learning Angular - Fourth Edition
Published in: Feb 2023Publisher: PacktISBN-13: 9781803240602
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (2)

author image
Aristeidis Bampakos

Aristeidis Bampakos is a Web Development Team Lead at Plex-Earth who specializes in the development of web applications with Angular. He has been an Angular Google Developer Expert (GDE) since 2020 and works as an Angular Senior Tech Instructor at Code.Hub, a private educational institute, where he nurtures aspiring Angular developers and professionals. He is also the author of Angular Projects with Packt.
Read more about Aristeidis Bampakos

author image
Pablo Deeleman

With sound expertise in front-end libraries and frameworks such as Backbone.js, Knockout.js, VueJS, React, Svelte, AngularJs, and Angular, Pablo Deeleman has developed his career since 1998 as a JavaScript engineer across a broad range of successful companies such as Gameloft, Red Hat or Dynatrace, just to name a few. He currently works as Staff Software Engineer at Twilio, the global leader in customer engagement communications. Pablo Deeleman has contributed to the dev community with several books on Angular since 2016, all published by Packt Publishing.
Read more about Pablo Deeleman