1. Home
Angular

Angular Tutorial: A Complete Guide to Creating Single-Page Applications

Master Angular with our concise guide, from setting up your environment to deploying production-ready apps.

  • 8 Lessons
  • 2 Hours
right-top-arrow
4

Angular Components: A Guide to Building Dynamic Web Applications

Updated on 13/09/2024422 Views

Introduction

Imagine yourself making a complicated Lego structure. Instead of using only one massive brick, you would use a whole variety of smaller, reusable bricks to build the different parts – the wheels, body, and roof. This modular approach thus makes the building (and rebuilding) process faster and more convenient.

Angular components are developed using the same approach. They are the basic units of Angular applications. Every sub-component is a separate user interface functionality that you can reuse, maintain easily, and separate from your codebase.

For instance, let us focus on a to-do list application. You might have separate components for:

  • The header: The app title is shown there.
  • The task list: To present the task list with checkboxes.
  • The task input: One of the ways to add tasks.

Each element will be responsible for its view (the visual elements displayed on the screen) and its logic (the code determining how the component should act). 

This modular approach offers several advantages:

Reusability: These components can be used in multiple places within the same or different applications, thereby saving time and avoiding code duplication. Imagine that the whole thing is reused as the main to-do list view and as a ‘completed tasks’ section.

Maintainability: By specifying clearly defined features for each component, they become easier to grasp, change, and verify. You will be able to change the task list display only by modifying the task list component code instead of modifying the whole application.

Modularity: Modules make it easier to ensure the codebase is well-organized and modular. This also simplifies the Angular components lifecycle of large projects and prevents the situation where a change to the code introduces unintended side effects.

With good use of Angular components, you can construct powerful web applications that are dynamic, scalable, and maintainable.

Building Your First Angular Component: Dive In

Before we plunge into the interesting area of building reusable components in Angular, let us ensure that we have the required tools at our disposal. Here's a step-by-step guide to setting up your development environment and creating component in Angular:

Installation of the Angular CLI (Command Line Interface)

The Angular CLI is your assistant who handles the creation, development, and deployment of your Angular apps. To install it globally using npm (Node Package Manager), open your terminal and run the following command:

Bash

npm install -g @Angular/cli

Once the installation is complete, verify it by running:

Bash

ng version

This will indicate the version of npm that is installed.

Building a New Angular Project

Now, let's create a brand new Angular project with the CLI already configured! In your terminal, navigate to your desired project directory and run the following command:

Bash

ng new my-first-Angular-app

Replace ‘my-first-Angular-app’ with the name of your project of choice.

CLI will walk you through other configurations, but the default settings are usually fine for our purposes. This command will be used to generate the basic file structure and install all the required dependencies.

Congratulations! You have established your development environment and have generated an Angular project. Now, we are ready to explore the building blocks of this project: Angular components.

Communication between Components

So, now that you have understood the components part, let's delve into how they interact using component communication in Angular. This two-way communication is a key component of the creation of Angular applications that are interactive, dynamic, and user-friendly.

Suppose you are developing an e-commerce app. You can show the product list section with different goods. The user clicks on the product, which takes them to the product details component. As the components interact, communication has to take place.

There are two primary mechanisms for components to talk to each other: 

  • Event Emitters
  • Event Listeners

Event Emitters are like a messenger that communicates to the parent component when a particular event is happening in the child component.

Event listeners on the parent component work as receivers, and they simply wait for the events and perform the action.

Parent-child Communication

Let's think about a case where a child component (product-card) sends an event upon a button click, while the parent component (product-list) captures this event and displays specific information about the selected product.

Here's a code example demonstrating this concept:

TypeScript

// product-card.component.ts

@Component({

  selector: 'app-product-card',

  templateUrl: './product-card.component.html',

  styleUrls: ['./product-card.component.css']

})

export class ProductCardComponent {

  @Input() product: Product; // Data passed from parent component

  @Output() productSelected = new EventEmitter<Product>(); // Event Emitter

  onProductSelect() {

    this.productSelected.emit(this.product); // Emitting the selected product

  }

}

// product-list.component.ts

@Component({

  selector: 'app-product-list',

  templateUrl: './product-list.component.html',

  styleUrls: ['./product-list.component.css']

})

export class ProductListComponent {

  products: Product[] = [

    // Array of products

  ];

  onProductSelection(product: Product) {

    console.log('Product selected:', product);

    // Display product details logic here

  }

In this case ‘product-card.component.ts’ is emitting a ‘productSelected’ event whenever ‘onProductSelect’ function is called. The parent component, ‘product-list.component.ts’, registers for this event using the (productSelected) event binding in the template and calls the ‘onProductSelection’ function to handle the selected product.

Child-parent Communication

Parent-child communication is more frequent, whereas child-to-parent communication also has its cases. For example, the following code can be used when a child component (modal) has a 'close' button. The button after a click should initiate an action in the parent component which will further close the modal.

The concept remains similar. The child component sends an event, and the parent component receives and reacts to it.

Advanced Component Features

Apart from these fundamental aspects, the templates of the Angular component allow a syntax that is very rich in building dynamic UIs. Let's delve deeper into some key concepts:

Component Templates: A World of Orders

Directives are signs in your template that change the DOM in a particular way, depending on certain conditions. Angular supplies a lot of directives that are built-in and simplifies the common tasks. Here are a few noteworthy ones:

1. NgIf

It helps you render elements using conditional rendering based on a given boolean expression. Let's say you have the product list component in which only the ‘Product Not Found’ message is displayed when there are no products to show. Here's how you can achieve this using NgIf:

HTML

<div *ngIf="!products.length">

Product Not Found

</div>

<ul *ngIf="products.length > 0">

</ul>

2. NgFor

It traverses the array of data and inserts the elements for each item. Most of the time you will either show a list of the product, customer information, or times when you need to iterate over an array.

HTML

<ul>

<li *ngFor="let product of products">{{ product.name }}</li>

</ul>

3. NgSwitch

This renders different parts of the template as a value of the property. This is meaningful for scenarios where it is desirable to show different content based on a situation.

HTML

<div [ngSwitch]="switchExpression">

  <ng-container *ngSwitchCase="caseValue1">

    </ng-container>

  <ng-container *ngSwitchCase="caseValue2">

    </ng-container>

  <ng-container *ngSwitchDefault>

    </ng-container>

</div>

Understanding Directive Types

Directives come in two flavors: structural and attribute.

  • Structural Directives: The specified directives are the ones that are responsible for the significant change of the DOM structure by adding, removing, or replacing elements. NgIf and NgFor are powerful structural directives that are the core of Angular.
  • Attribute Directives: Among these directives, the ones that change the attributes of the already existing DOM elements are the most common. The NgClass directive is a common example that dynamically adds/removes classes based on given conditions.

Component Styles: Customizing the Look and Feel

Components are the ones who do the job for you by specifying the styles for that component. This leads to modularity and having all the styles of your project well-arranged. You can include styles directly within the component using the styles property of the @Component decorator:

TypeScript

@Component({

  selector: 'app-product-card',

  template: `

    <div class="product-card">

      </div>

  `,

  styles: [`

    .product-card {

      border: 1px solid #ddd;

      padding: 10px;

    }

  `]

})

export class ProductCardComponent {

  // ...

}

This way you cannot access the styles by your component. Alternatively, you can take the route of creating separate CSS files for complex styling reasons.

Services and Dependency Injection (DI)

Consider that you are developing an e-commerce app. Both the product list component and shopping cart component must be able to handle product data. Instead, you would store the data in each element, which not only duplicates the data but also makes it complex and prone to errors. Services are the ones that will save you  the day!

Services are the reusable classes that create objects for functionalities and data sharing among multiple components. Dependency Injection (DI) is a design pattern that provides instances of services to those components that require them. This whole process ensures code reusability, maintainability, and testability.

Here is a simplified example:

  • Create a ProductService, whose purpose is to fetch product data from an API (logic for it).
  • Give the ProductService injection into both ProductList and ShoppingCart.
  • The injected components in turn may call methods on the service to obtain product details.

Maintaining a single source of truth without redundancy is achieved through the separation of product data and logic from the components.

Forms in Angular Components

Interactive forms are a central tool of many web applications. Angular provides two primary approaches for building forms: template-driven forms and reactive forms.

  • Template-driven forms: It is simpler to set up and convenient for simple forms. Data binding is directly handled by the component's template using directives such as ngModel.
  • Reactive forms: It helps improve the granular control while being more suitable for complex forms with validation needs. Data is modeled as FormGroup and FormControl classes, which separate the presentation logic from the view.

Here is a code snippet demonstrating a reactive form with validation:

TypeScript

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

import { FormBuilder, FormGroup, Validators } from '@Angular/forms';

@Component({

  selector: 'app-reactive-form',

  templateUrl: './reactive-form.component.html',

  styleUrls: ['./reactive-form.component.css']

})

export class ReactiveFormComponent {

  myForm: FormGroup;

  constructor(private fb: FormBuilder) {

    this.myForm = this.fb.group({

      name: ['', Validators.required],

      email: ['', [Validators.required, Validators.email]],

    });

  }

  onSubmit() {

    console.log(this.myForm.value);

  }

}

This example is a FormGroup with controls of name and email. Validators can be used to apply validation rules. Form submission and form data retrieval logic are handled by component logic using myForm.value property.

With the proper use of services and forms, you can develop complex, scalable, and maintainable Angular applications that efficiently manage data and user interactions.

Code Organization Within Components

Your component's code needs to be clean and well-organized for ease of reading and maintainability. Here is the concept of Separation of Concerns (SoC) applied to components:

  • Template Logic: Concentrates on the visual coloring of the element through HTML as well as Angular directives.
  • Component Logic: It manages the code written in TypeScript that handles the component's functionalities like processing of the data, handling of events, and interactions with services.

Example: Separation of Concerns

Imagine a product review with rating stars. The template would be in charge of producing the stars using HTML and ngFor directives.

The logic component, written in TypeScript, would take care of the average rating calculation and put stars in their places.

You do this by allowing the template to remain the sole focus on presentation and the component class to remain the single focus on functionality. This also leads to an improvement in the code readability and the component can be modified either visually or functionally as the cases may be.

Using Interfaces For Data Modeling

Interfaces are like data-building plans that define the structure of the data. They are used for:

  • Writing readable code by using the @property decorator, which clarifies the properties and type of data.
  • Improving type safety and preventing errors that might appear during development.

Example: Using an Interface

Imagine a Product interface for your e-commerce application:

TypeScript

interface Product {

  id: number;

  name: string;

  description: string;

  price: number;

}

This interface describes the characteristics the ‘Product’ object should have. Through this interface, you will be able to type safely and also make your code more readable.

Wrapping Up: The Foundation of Building Blocks

Throughout this blog, we have explored the fundamentals of Angular components: their organization, communication channels, and good governance.

Recap: The Angular Component Toolkit

  • We figured out the role of reusable component in Angular and how it separates presentation logic (templates) from component logic (TypeScript classes).
  • Event emitters and event listeners were brought into the picture, which allows components to communicate and exchange data.
  • We went through code organization techniques and optimal approaches that are used for the creation of maintainable and effective components.

Through learning Angular standalone components, you will be able to build fascinating and responsive web pages. Components are a basis for creating SPAs (Single-Page Applications) that encourage good user experience.

FAQs

1. What are Angular components?

Angular components are the basic Angular application building material. They are reusable, self-contained modules of code that are responsible for functionalities like HTML templates, CSS styles, and TypeScript code. Parts make it possible for developers to build complex UIs that are easy to manage and are divided into simple and independent components.

2. Why is Angular component-based?

Angular embraces the component-based approach as it follows the principles of component-based architecture that advocate for modularity, reusability, and maintainability. The Angular framework allows developers to split the user interface into small, independent components. It helps developers finish complex applications more quickly, improving code readability and promoting collaborative development.

3. What is an Angular component and a module?

An Angular component is a TypeScript class that is marked up with the `@Component` decorator and represents a particular portion of the user interface. It has a template, styles, and logic to define its behavior. 

On the other hand, an Angular module is a container for all the components, directives, pipes, and services that are related to each other. Modules assist in making the application consistent and make the loading process smoother for better performance.

4. What is the distinction between React and Angular components?

Both React and Angular apply a component-based approach, but there are some disparities between the ways they implement components. In React, components are usually defined as JavaScript functions or classes, and JSX is used to represent the template of the component. However, in Angular components, type script classes are defined with the `@Component` decorator, and the template, styles, and logic are held inside the component.

5. What are the different types of Angular components?

In Angular, there are mainly three types of components:

  • Root Component: The top-level component that catalyzes our Angular application.
  • Module Components: Parts that are declared inside the Angular modules for organizing the related function in Angular.
  • Child Components: Components that are nested inside other components and can be used to create hierarchical structures and encapsulate the functionality.

6. How to create components in Angular?

To write a dynamic component in Angular, you can use the Angular CLI (Command Line Interface) or write all the necessary files by yourself. Using the Angular CLI, you can run the following command:

ng generate component component-name

This directive will create all the necessary files for the component, including TypeScript, HTML, CSS, and a test file.

7. How to add two components in Angular?

You can include two components in Angular by using the selector tags in the template of a parent component. For example, if you have two components named `app-component1` and `app-component2`, you can include them in the template of a parent component as follows:

HTML

<app-component1></app-component1>

<app-component2></app-component2>

8. Can we build multiple components in Angular?

Yes, it is possible to create a variety of components in Angular. Usually, Angular applications are composed of several components that function together to build the user interface. Every piece of the UI is either a discrete part and is used in different parts of the application, or a unified one that covers a specific part.

Rohan Vats

Rohan Vats

Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

Need More Help? Talk to an Expert
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...