Angular 15 Basics Tutorial by Example

Angular 15 Basics Tutorial by Example

In this tutorial, we'll build a web application with Angular 9. Meanwhile, we'll learn about the fundamental concepts which you will need to know to do front-end web development with Angular, such as:

  • components, pipes, directives, services, and modules,
  • component communication via @Input and @Output decorators,
  • displaying data via interpolation and the ngFor/ngIf directives,
  • property and event bindings,
  • accessing the DOM,
  • getting and submitting user input with Angular forms,
  • sending HTTP requests with Angular HttpClient and RxJS Observables and operators,
  • styling with CSS and ngClass and ngStyle directives,
  • building production bundles and deploying to Firebase.

We'll use the online StackBlitz IDE, so head over there, register a new account using GitHub and START A NEW APP then choose the Angular workspace.

Angular 15

  • Note: It's officially recommended to use Angular CLI to create and build Angular projects. You'll need to have a recent version of Node and NPM installed on your machine before you can install the CLI from npm using the npm install -g @angular/cli command. But since this is our first app with Angular, let's keep it simple and use the online IDE. You can then export an app from StackBlitz to your local environment, simply refer to the Deployment section below.

What is Angular?

Let's get started by defining Angular, what is it and what its advantages?

Angular is a JavaScript framework written in a language called typescript (a compiled, typed and super language of JavaScript), used to create user interfaces or frontend apps, and was created by Google on October 20, 2010.

Angular is used to build web and mobile applications (Together with the Ionic framework).

Also, Angular is based on the SPA concept, i.e. it is used to build a single page application where the modules are loaded all at once from the browser and there is no need to load the page again while moving between pages, because inside Angular there is a client-side router abstraction, that works as a mediator that directs the browser during any process of moving from one page to another page.

Among the advantages of Angular is that it has very impressive micro services and fundamentals in terms of controlling the http services and methods where you can control the way to communicate with any external or internal API and allows a granular control of the request and the return response, and also there is a library called rxjs (reactive extensions for JavaScript)- This library and the operations inside it are used to control the creation of the asynchronous operations, whether inside Angular or in another API, such as observable, carchError, of, and many other operators.

Angular uses a command-line tool called the Angular cli, which is a very important tool. Without it, things can be difficult. One of its benefits is that you can generate components, services, models, modules, and many files only via a specific command. For example:

ng generate component myComponent

This command will generate a component with an html file, typescript file, css/sass file and unit testing file, all with just one command.

Angular uses a design pattern called the Singleton, meaning that there is a root module which is the basic module in the app and is called app.module by convention, and sub-modules that are used depending on the need of the system and are added in order to provide a commonly required functionality like routing, form processing, http requests, etc. These sub-modules must be defined inside the root module so the system can identify them.

Angular enables an RBA system, i.e role based authorization system.

You can create various artifacts with services, guards, and pipes, in order to create "guards" on each route in your user interface in order to make sure that the user has the the authorization to access a view.

Angular provides a great methodology of connecting data between html templates and typescript via something called property binding so that you can link data easily without the need for libraries like the jquery or native JavaScript APIs for directly accessing the DOM.

Angular also provides a very powerful method for creating and validating forms, and it has two methodologies for creating forms, the first methodology is called template-driven forms and the other one is called reactive forms which is built using an API called the form builder.

Angular services are classes that can be shared between more than one module and component and can encapsulate several methods, It can be used for common functionalities such as data retrieval, modification or deletion or other things. Services use the @Injectable decorator so they can be injected in any component or service via the Angular dependency injector.

Angular provides more than that, and with its multiple versions, more features are being added. With the latest Angular 15 version, a next generation compilation and rendering pipeline called Ivy is used by default. The final bundles are smaller and runtime performance is better than it was previously during the production process.

Who’s this Tutorial for?

Angular Versions

In Software Development, apps are versioned by following Semantic Versioning, which is simply a convention that everyone starts to follow.

Angular also follows semantic versioning which has a Major.Minor.Patch format. We increment a specific section when there is a major, minor or patch release:

Major Release — The Major part is incremented by one if the new features break backwards compatibility,

Minor Release — The Minor part is incremented by one if the new features don’t break any existing features,

Patch Release The Minor part is incremented by one 1 for releasing patch fixes.

The Angular team releases a new major version each six months and the last version, as of this time, is Angular 8:

You can follow with the latest versions from the CHANGELOG.

Prerequisites

You’ll need to have some prerequisites to follow this tutorial:

  • Working knowledge of the tree pillars of the web i.e Javascript, HTML & CSS,
  • Working knowledge of TypeScript and OOP programming (Classes and Decorators),
  • Recent versions of Node and NPM (v 10+) for local development.

Angular Modules

Angular projects adhere to a modular and component-based architecture.

According to Wikipedia:

  • Modular programming is a software design technique that emphasizes separating the functionality of a program into independent, interchangeable modules, such that each contains everything necessary to execute only one aspect of the desired functionality.

Angular makes it easy to create modules by providing NgModules:

A NgModule is a TypeScript class decorated with the @NgModule decorator which takes a few metadata that does the following:

  • Declares which components, directives, and pipes belong to the module.
  • Makes some of those components, directives, and pipes public so that other module's component templates can use them.
  • Imports other modules with the components, directives, and pipes that components in the current module need.
  • Provides services that the other application components can use.

Every Angular app has at least one module, conventionally called the root module. This is the module that gets bootstrapped for running the application.

Head over to your Angular project in the Stackblitz IDE. Open the src/app/app.module.ts file, you should see the following code:

import { NgModule } from '@angular/core';

import { BrowserModule } from '@angular/platform-browser';

import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';

import { HelloComponent } from './hello.component';

@NgModule({

imports: [ BrowserModule, FormsModule ],

declarations: [ AppComponent, HelloComponent ],

bootstrap: [ AppComponent ]

})

export class AppModule { }

At the top, we have some import statements. NgModule belongs to the @angular/core package.

After the imports, we configure the module by decorating the AppModule class with @NgModule and stating what components and directives belong to it (In the declarations array) as well as which other modules it uses (In the imports array). For more information on the structure of an @NgModule, you can read Bootstrapping from the official Angular guide.

There is more that you should know about modules but let's leave that to after you build your first app.

Angular Components

Now, let’s get to other piece of the puzzle or components. Simply put, a component controls a part of the UI of your application. For example, the header, footer, or whole page can all be components. Depending on how much reusability, you want in your code.

Technically, an Angular component is a TypeScript class decorated with the @Component decorator which is part of the Angular core.

A component has an associated view which is simply an HTML file (but can also contain some special Angular template syntax which helps display data and bind events from the controller component)

A component has also one or more associated stylesheet files for adding styles to the component view. These files can be in many formats like CSS, Stylus, Sass or Less.

Head back to your project in Stackblitz, open the src/app/app.component.ts file, you should find the following code:

import { Component } from '@angular/core';

@Component({

selector: 'my-app',

templateUrl: './app.component.html',

styleUrls: [ './app.component.css' ]

})

export class AppComponent {

name = 'Angular';

}

In this file, we export the AppComponent class, and we decorate it with the @Component decorator, imported from the @angular/core package, which takes a few metadata, such as:

  • selector: this allows you to invoke the component from an HTML template or file just like standard HTML tags i.e: ,
  • templateUrl: This is used to tell the component where to find the HTML view,
  • styleUrls: This is an array of relative paths to where the component can find the styles used to style the HTML view.

AppComponent is the root component of our application. It’s the base of the tree of components of our application and it’s the first component that gets inserted in the browser DOM. Read The bootstrap array.

An Angular application is composed of a tree of components, in which each Angular component has a specific purpose and responsibility.

A component is comprised of three things:

  • A component class, which handles data and functionality. In the previous section, the product data and the share() method were defined for you in the component class.
  • An HTML template, which determines what is presented to the user. In the previous section, you modified the product list's HTML template to display the name, description, and a "Share" button for each product.
  • Component-specific styles that define the look and feel. The product list does not define any styles.

Currently, our app has three components:

  • app-root (orange box) is the application shell. This is the first component to load, and the parent of all other components. You can think of it as the base page.
  • app-top-bar (blue background) is the store name and checkout button.

The Component’s Input and Output

Angular Services

After understanding modules and components, let’s see what services are.

In Angular, a service is a singleton that can be wired with components or other services via Dependency Injection.

According to Wikipedia:

  • In software engineering, dependency injection is a technique whereby one object supplies the dependencies of another object.

Don’t be intimidated by this term, it simply means that Angular (or a part of Angular, the injector) takes care of instantiating the services and provides the instance to the requesting component.

According to the Angular docs:

  • DI is wired into the Angular framework and used everywhere to provide new components with the services or other things they need. Components consume services; that is, you can inject a service into a component, giving the component access to that service class.

You can use services to organize and share code across your app

Typically, a component's job is to enable the user experience and nothing more. A component should present properties and methods for data binding, in order to mediate between the view (rendered by the template) and the application logic.

A component can delegate certain tasks to services, such as fetching data from the server, validating user input, or logging directly to the console.

By defining such processing tasks in an injectable service class, you make those tasks available to any component.

To define a class as a service in Angular, use the @Injectable() decorator to provide the metadata that allows Angular to inject it into a component as a dependency.

You need to provide a service before it can be available. This can be done in three ways:

  • Via the service’s metadata passed to the @Injectable() decorator (The service will be available everywhere),
  • Via the providers array, in a specific module (The service is available only to the components and services of the module),
  • Via the providers array in a specific component (The service is available only to the component).

Angular Template Syntax

Angular has its own template syntax which extends HTML with a set of useful directives that make it easy for developers to render data from the component in the view.

These are the common features of Angular's template syntax:

  • Interpolation using . For example ,
  • Property binding [ ],
  • Event binding ( ),
  • *ngFor for iterating over arrays of data,
  • *ngIf for conditionally rendering a part of the view.

Angular Directives

The Angular directive helps us to manipulate the DOM. You can change the appearance, behavior or a layout of a DOM element using the Directives. They help you to extend HTML. The Angular directives are classified into three categories based on how they behave. They are Component, Structural and Attribute Directives

The ngFor is an Angular structural directive, which repeats a portion of HTML template once per each item from an iterable list (Collection). The ngSwitch allows us to Add/Remove DOM Element. It is similar to switch statement of C#. The ngIf allows us to Add/Remove DOM Element.

The ngClass Directive is an Angular Attribute Directive, which allows us to add or remove CSS classes to an HTML element. The ngStyle directive allows you to modify the style of an HTML element using the expression. Using the ngStyle you can dynamically change the style of your HTML element.

  1. Angular Directives
  2. ngFor
  3. ngSwitch
  4. ngIf
  5. ngClass
  6. ngStyle

Angular Pipes

The Angular pipes are used to Transform the Data. For Example, the Date pipe formats the date according to locale rules. We can pass arguments to pipe and chain pipes. The Angular also allows us to create the Custom Pipe

  1. Angular Pipes
  2. Angular Custom Pipes