Table of contents
1.
Introduction
2.
What are Angular Components Overview?
3.
Component Lifecycle
3.1.
Data Binding
4.
Child Component
5.
Creating a Component in Angular 8
5.1.
Steps to Create a Component
5.2.
Generate a Component
5.3.
Structure of a Component
5.4.
Editing the HTML Template
5.5.
Adding Styles
6.
Using a Component in Angular 8
6.1.
Steps to Use a Component
6.2.
Use the Component in HTML
6.3.
Run the Application
7.
Implementation Code
7.1.
1. Component Class
7.2.
2. HTML Template
7.3.
3. Styles
7.4.
4. App Component
8.
Demo: Creating an Angular Component
8.1.
Step 1: Set Up Your Angular Project
8.2.
Step 2: Generate a New Component
8.3.
Step 3: Understand the Generated Files
8.4.
Step 4: Add Content to the Component
8.5.
Step 5: Use the Component in Your Application
8.6.
Step 6: Add Logic to the Component
9.
Frequently Asked Questions
9.1.
What is the role of a selector in an Angular component?
9.2.
Can a component have multiple templates?
9.3.
How do you share data between components?
10.
Conclusion
Last Updated: Jan 25, 2025
Easy

Angular Components Overview

Author Pallavi singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Components in Angular are the building blocks of any Angular application. They are responsible for managing the UI and the logic of a specific part of the application. Each component consists of a template (HTML), a class (TypeScript), and metadata (decorators) that define its behavior and structure. Components make it easy to create reusable and modular pieces of code, enhancing maintainability and scalability.

Angular Components Overview

In this article, we will discuss what are Angular Components Overview, how to create them, and how to use them effectively. 

What are Angular Components Overview?

Angular components are the fundamental building blocks of an Angular application. They are like small, reusable pieces of code that control a part of the user interface. Each component consists of three main parts: the template, the class, & the metadata.

1. Template: This is the HTML part of the component. It defines what the user sees on the screen. The template can include regular HTML & Angular-specific syntax like directives & bindings.
 

2. Class: This is the TypeScript part of the component. It contains the logic & data that the template uses. The class is defined using the `@Component` decorator.

 

3. Metadata: This is the information that Angular uses to configure the component. It is provided using the `@Component` decorator. Metadata includes things like the selector, template URL, & style URLs.

For example, a simple component might look like this:

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


@Component({
  selector: 'app-root',
  template: `<h1>Hello, World!</h1>`,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'my-app';
}


In this example, the `@Component` decorator tells Angular that this class is a component. The `selector` is used to include this component in other templates. The `template` defines the HTML that will be displayed.

Component Lifecycle

Angular components follow a structured lifecycle, consisting of several stages where specific actions can be performed. These stages are controlled by lifecycle hooks that developers can use to manage tasks such as initialization, change detection, and cleanup.

Here are the key lifecycle hooks:

  • ngOnInit: This hook is called after Angular initializes the component's input properties and the component's view. It is commonly used to set up data or perform tasks that need to happen when the component loads.
     
  • ngOnChanges: Triggered whenever the component's input properties change. It is useful for responding to updates in data that the component receives from a parent.
     
  • ngOnDestroy: This hook is executed just before the component is removed from the DOM. It is ideal for cleaning up resources like subscriptions or event listeners to prevent memory leaks.
     

These lifecycle hooks allow developers to have fine-grained control over how components behave during their lifecycle.

Data Binding

Data binding in Angular is a mechanism that connects the component's data and the DOM, enabling seamless communication between the view and the component's logic. Angular provides four types of data binding:

Interpolation:

Syntax:

 {{ expression }}

 

  • Used to display component data within the view.

Example:

<p>{{ title }}</p>

 

Property Binding:

Syntax: 

[property]="expression"

 

  • Binds a DOM property to a component property.


Example:

<img [src]="imageUrl" />

 

Event Binding:

Syntax: 

(event)="methodName()"

 

  • Listens to user events like clicks and binds them to component methods.


Example:

<button (click)="handleClick()">Click Me</button>

 

Two-Way Binding:

Syntax: 

[(ngModel)]="property"


Synchronizes the data between the component and the view in both directions.


Example:

<input [(ngModel)]="username" />
<p>{{ username }}</p>

 

By combining lifecycle hooks and data binding, Angular makes it easier to manage dynamic user interfaces and application logic, ensuring that the view and the component stay in sync.

Child Component

A child component is a component that is nested inside another component. It is useful for breaking down complex UIs into smaller, reusable parts. In the above example:

  • The UserDetailsComponent acts as a child of the AppComponent.
     
  • Data is passed from the parent to the child component using the @Input() decorator.
     

To further understand child components, here’s a simple use case where a parent component sends an array of users to a child component for display:

1. Modify the child component to handle an array:

@Input() users!: { name: string; age: number }[];


2. Update user-details.component.html to display the list:

<div *ngFor="let user of users">
  <p>Name: {{ user.name }}, Age: {{ user.age }}</p>
</div>


3. Update the parent component:

users = [
  { name: 'Alice', age: 24 },
  { name: 'Bob', age: 27 }
];


4. Pass the array to the child component:

<app-user-details [users]="users"></app-user-details>

Creating a Component in Angular 8

A component in Angular is a TypeScript class with a decorator @Component. This decorator includes metadata such as the selector, template, and styles. Angular components make it easy to manage the UI and behavior of your application.

Steps to Create a Component

Install Angular CLI
Ensure you have the Angular CLI installed. You can install it using the following command:

npm install -g @angular/cli

Generate a Component

Use the CLI to create a component with the command:
ng generate component component-name

For example:
ng generate component user-profile

This command creates the following files in the src/app/user-profile/ directory:

  • user-profile.component.ts (Logic)
     
  • user-profile.component.html (Template)
     
  • user-profile.component.css (Styles)
     
  • user-profile.component.spec.ts (Test)

Structure of a Component

The primary file for a component is user-profile.component.ts. It looks like this:

import { Component } from '@angular/core';
@Component({
  selector: 'app-user-profile',
  templateUrl: './user-profile.component.html',
  styleUrls: ['./user-profile.component.css']
})
export class UserProfileComponent {
  userName: string = 'John Doe';
  userAge: number = 25;

  getUserInfo() {
    return `Name: ${this.userName}, Age: ${this.userAge}`;
  }
}

Editing the HTML Template

Modify the user-profile.component.html file to display the user’s information:

<div>
  <h1>User Profile</h1>
  <p>{{ getUserInfo() }}</p>
</div>

Adding Styles

Update the user-profile.component.css file to style the component:

h1 {
  color: blue;
}

p {
  font-size: 18px;
}

Using a Component in Angular 8

Once a component is created, it needs to be included in the Angular module and used in a parent component.

Steps to Use a Component

Add the Component to a Module

Open the app.module.ts file and ensure your component is declared:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { UserProfileComponent } from './user-profile/user-profile.component';


@NgModule({
  declarations: [
    AppComponent,
    UserProfileComponent
  ],
  imports: [BrowserModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Use the Component in HTML

The selector defined in the component decorator is used as a custom HTML tag.
Add the component to the app.component.html file:

<div>
  <h1>Welcome to Angular App</h1>
  <app-user-profile></app-user-profile>
</div>

Run the Application

Start the development server to view your component in action:

ng serve

 

Open the browser at http://localhost:4200. You’ll see:

Welcome to Angular App
User Profile
Name: John Doe, Age: 25

Implementation Code

Here’s a complete example of creating and using a component in Angular:

1. Component Class

import { Component } from '@angular/core';
@Component({
  selector: 'app-user-profile',
  templateUrl: './user-profile.component.html',
  styleUrls: ['./user-profile.component.css']
})
export class UserProfileComponent {
  userName: string = 'Alice';
  userCity: string = 'New York';


  getUserDetails() {
    return `Name: ${this.userName}, City: ${this.userCity}`;
  }
}

2. HTML Template

<div>
  <h2>Profile Details</h2>
  <p>{{ getUserDetails() }}</p>
</div>

3. Styles

h2 {
  color: green;
}
p {
  font-size: 16px;
  font-family: Arial, sans-serif;
}

4. App Component

<div>
  <h1>Angular Components Demo</h1>
  <app-user-profile></app-user-profile>
</div>

Demo: Creating an Angular Component

Now that we understand what Angular components are, let’s create one from scratch. This step-by-step guide will help you build your first Angular component & understand how it works.

Step 1: Set Up Your Angular Project

Before creating a component, you need an Angular project. If you don’t have one, you can create it using the Angular CLI. Open your terminal & run the following command:

ng new my-first-app


This command creates a new Angular project named `my-first-app`. Navigate to the project folder:

cd my-first-app

Step 2: Generate a New Component

Angular CLI makes it easy to create components. To generate a new component, run the following command:

ng generate component my-first-component


This command creates a new folder named `my-first-component` inside the `src/app` directory. It also generates four files:

1. my-first-component.component.ts: The TypeScript file for the component.
 

2. my-first-component.component.html: The HTML template for the component.
 

3. my-first-component.component.css: The CSS file for styling the component.
 

4. my-first-component.component.spec.ts: A test file for the component.

Step 3: Understand the Generated Files

Let’s take a closer look at the `my-first-component.component.ts` file:

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


@Component({
  selector: 'app-my-first-component',
  templateUrl: './my-first-component.component.html',
  styleUrls: ['./my-first-component.component.css']
})
export class MyFirstComponentComponent {
  // Component logic goes here
}

 

  • `selector: 'app-my-first-component'`: This is the custom HTML tag that Angular uses to include this component in other templates.
     
  • `templateUrl: './my-first-component.component.html'`**: This points to the HTML file that defines the component’s view.
     
  • `styleUrls: ['./my-first-component.component.css']`**: This links the CSS file for styling the component.

Step 4: Add Content to the Component

Open the `my-first-component.component.html` file & add some HTML:

<h2>Welcome to My First Component!</h2>
<p>This is a simple Angular component.</p>

 

You can also add some styles in the `my-first-component.component.css` file:

h2 {
  color: blue;
}
p {
  font-size: 18px;
}

Step 5: Use the Component in Your Application

To display this component, open the `app.component.html` file & add the component’s selector:

<app-my-first-component></app-my-first-component>


When you run your Angular application using the command `ng serve`, you will see the following output in your browser:

Welcome to My First Component!
This is a simple Angular component.

Step 6: Add Logic to the Component

You can also add logic to your component. For example, let’s add a property to the `MyFirstComponentComponent` class:

export class MyFirstComponentComponent {
  message = 'This message is from the component class!';
}


Now, update the `my-first-component.component.html` file to display this message:

<h2>Welcome to My First Component!</h2>
<p>{{ message }}</p>


The double curly braces `{{ }}` are used to bind data from the component class to the template. When you run the application, you will see:

Welcome to My First Component!
This message is from the component class!

Frequently Asked Questions

What is the role of a selector in an Angular component?

The selector acts as a custom HTML tag to include the component in templates.

Can a component have multiple templates?

No, a component can only have one template, but you can use directives to conditionally render parts of it.

How do you share data between components?

Use Input and Output decorators to pass data and events between parent and child components.

Conclusion

Components are essential in Angular to build modular, maintainable, and reusable parts of your application. They separate logic, UI, and styles, making the development process organized and efficient. In this article, we covered how to create, use, and implement Angular Components Overview, complete with examples and code.

Live masterclass