Learn Angular for Back-End Developer (Part 3)-Angular Fundamentals

The main Angular building blocks explained with simple examples

Abdelmajid BACO
8 min readNov 20, 2020

In this article I’m going to introduce the fundamentals of building applications with Angular. By the end of this article we will understand the basic Angular building blocks such as: Components, Modules, Templates, Data-Binding, Directives, Services and Dependency Injection.

This article is the continuation of two articles already published about learning Angular for Back-End developer. The Part 1 was a quick introduction to Angular, in which I explained step-by-step how to set up our development environment? How to create and serve our first application using Angular-CLI? How the Angular project is structured? … The Part 2 was about Typescript language, where I introduced notions like Interfaces, Classes, Properties, Modules, Arrow Functions and so on.

The Main Angular Building Blocks

Components

Every Angular app has at least one component called app or root component, a component encapsulates data, HTML template and the logic for the view. Look at this image below, it’s a screen shot of angular website, we can break this view into smaller views or components: the yellow component that represents Navbar, the red component that represents Sidebar and the green component that represents an area to display content.

Angular App is a tree of components starting from the root component.
Angular website with potential components

A real world Angular App is a tree of components starting from the root component.

Modules

Module is a container of related components or domains, for example Angular framework has RouterModule which provides all the routing mechanism. Every Angular app has at least one module called AppModule. This module is responsible for launching the application.

Templates

The template represents the component view, it can combine HTML markup and Angular statements.

Directives and Data-Binding

Directive provides different ways to connect application data with the view, this connection is called Data-Binding.

Services

Components should not include any logic other than presentation logic, the details of getting data from a database or web API must be delegated to another element called Service.

Dependency Injection

This pattern is implemented with Angular framework to manage services and inject them inside the components.

Let’s learn about these building blocks in more details.

In the next chapters I assume that you have already learned my articles:

Create Components

Open your project hello-angular, already created in the first article here , in vscode, then run ng serve to serve the application Like this:

cd hello-angular
code .
-------------
ng serve

To create a new component called users we can use Angular CLI command like this:

ng g c users

g: which is short for generate

c: which is short for component

Angular CLI creating users component
Angular CLI creating users component

Angular CLI created a directory called users with four files for this component: a stylesheet file, a template html file, a spec file for unit tests and finally a Typescript file. It also updated app module and registered this new component.

Let’s take a look at the Typescript file below, it contains a class called UsersComponent, to identify this class as a component, Angular CLI added the @Component () decorator imported from the angular library called @angulare/code.

A component basic code
Users component class

This decorator function takes an argument, which is an object with three properties:

1- selector: that identifies the element name we can use to render users component.

2- templateUrl: the relative path or absolute URL of a template file for users component.

3-styleUrls: the relative path or absolute URL for file containing CSS stylesheets to use.

The component class implements an interface called OnInit used to perform some initialization tasks.

Note here that Angular CLI uses Pascal naming convention. The first letter of every word is capital and also by convention we use the suffix Component in the name of the class UsersComponent.

Modules

Now let’s take a look at app module, note that this module is decorated with another decorator called @NgModule().

Root Module basic code
Root Module

This decorator function takes and argument, which is an object with declarations property, this is where Angular CLI added all components that are parts of this module. As I said before, Angular Module is a container of related components. App Module is the root module of our application, it contains the root component AppComponent and the created component UsersComponent. AppComponentis also added to bootstrap property, so this component will be run first to render all the application.

Use Selector as an HTML Element

To add this component in an HTML markup we use its selector app-users Anywhere we have an element like <app-users> Angular is going to render the template of this component shown below:

External template for UsersComponent

Now we are going to add this element <app-users> in the external template for AppComponent as shown in the code below:

AppComponent
External template for AppComponent

Remember, an Angular App is a tree of components starting from the root component called AppComponent:

AppComponent
The root Component

The selector element <app-root> is rendered inside index.html, as shown in the following code:

index.html that contains the angular application
index.html that contains the angular application.

Now, our new home page look like this:

index.html markup
index.html

Inside de body element we have the selector <app-root>, and inside this, we have the template for AppComponent: h1 and <app-users> element. In the same way, inside the selector <app-users> we have the template for UsersComponent.

So, this is how Angular applications use selectors to render components.

But, how to render dynamic content with angular components?

Data-Binding

As I said before, Angular component encapsulates data, HTML template and the logic for the view. Data-Binding is a mechanism that creates a connection between the template and the data. When the data changes, the view is automatically notified and updated.

Let’s extend the UsersComponent and define a field in this class to hold the title as shown below:

UsersComponent with title field

To display this title in our template dynamically, we use a special syntax double curly braces {{}}, called string interpolation:

users component template

And this is the result in the browser:

browser result

Interpolation using {{}} is very powerful to display a simple field. However, how to display a list of values?

Structural Directives

Directive is one of the Angular building blocks, we use structural Directives to manipulate the DOM by adding, removing, and replacing elements.

*ngFor: is an iterative directive.

*ngIf: is a conditional directive.

Look at this following example:

Using ngIf and ngFor directives

The first div is rendered only if users filed is not empty, otherwise the second div is rendered. To display the list of users, ngFor will loop through the array of users and use interpolation to update the DOM. The following code is the new version of our UsersComponent.

UsersComponenet with users field array

In the real word applications, we get list of users from the server using another Angular building blocks called Service.

Creating Services

To create a new service called users we can use Angular CLI command like this:

ng g s users

g: which is short for generate

c: which is short for service

Angular CLI creating users service
Angular CLI creating users service

Angular CLI generates two files: one is for the actual service and the second is a spec file for unit tests.

Let’s take a look at the code of our new service, it contains a class called UsersService, by convention we use the suffix Service in the name of the class.

users service class

In this class we have another decorator called @Injectable (), which is imported from the angular library @angulare/code.

This decorator marks the class available to be injected as a dependency. The property providedIn is set to root, this means that the root Module will be the provider of the service.

I added a method called getUsers() to simulate the logic of consuming an http service.

Now, we have the service to get the list of users, in the next chapter, I will show you, how to use this service in our component?

Dependency Injection

We can use the constructor of our component to create an instance of the service. Then, we can call getUsers() to populate the users filed as shown in the following code:

call the service inside the component constructor

With this implementation the component and the service are tightly coupled. UsersComponent needs to create a concrete object of the service and manages its lifetime, all changes in the service can have an impact on the component, finally UsersComponent can’t be tested independently of the service.

To avoid these problems, we can delegate the creation of a new instance of the service to the Angular framework. This technique is called Dependency Injection. If you want to learn more about Dependency Injection, check out my previous article specifically on this topic:

Let’s refactor the UsersComponent class to allow Dependency Injection, as shown below:

use Dependency Injection to inject the service inside the component constructor

The constructor takes a parameter of type UsersService. With this, Angular will create an instance of the service and then inject it into the constructor of the component. Dependency Injection.

This is Dependency Injection with Angular. Easy! isn’t it?

Conclusion

That’s the end of this article, in which I’ve covered the main Angular building blocks. In my next article, I’ll address several subjects including event handling, binding and formatting data.

Thanks for reading. I hope this article was helpful to understand the main Angular building blocks.

Learn More / Resources

--

--

Abdelmajid BACO

Senior Full Stack .Net / Angular Developer, Cloud & Azure DevOps, Carrier Manager, Husband, and Father.