Angular - Components



Components are the building blocks of an Angular application. The primary use of Angular Component is to generate a section of web page called View. By combining different views, a single application is created. Every component will have an associated template and it will be called in order to generate views.

Let us learn the basic concept of components in this tutorial.

Structure of Angular Component

Each component of an Angular application has a few important parts which are as follows −

  • @component Decorator: All the application related configurations are written inside this decorator.

  • HTML Template: View of the Angular application.

  • Styles: It controls the styles of a view.

  • TypeScript Class: Code related to behavior of the Angular application goes into this class.

By default, all these parts are created by Angular CLI, you can update, add or even delete them if any of them is not required.

Component Structure

How to Create Components in Angular?

In Angular, a new Component is created using the ng generate component command as specified below −

ng generate component name-of-component

Example

Let's see an example where we create a new component in our ExpenseManager application. This component will contain our first expense entry. First, open the command prompt and navigate to ExpenseManager application.

cd expense-manager

Now, use the command given below to create a expense-entry component −

ng generate component expense-manager

Following files and folders will be created by Angular CLI on the above command −

CREATE src/app/expense-entry/expense-entry.component.html (28 bytes) 
CREATE src/app/expense-entry/expense-entry.component.spec.ts (671 bytes) 
CREATE src/app/expense-entry/expense-entry.component.ts (296 bytes) 
CREATE src/app/expense-entry/expense-entry.component.css (0 bytes) 
UPDATE src/app/app.module.ts (431 bytes)

Here,

  • ExpenseEntryComponent is created under src/app/expense-entry folder.
  • Component class, Template and stylesheet are created.

Next, we add a title property to ExpenseEntryComponent, i.e., (src/app/expense-entry/expense-entry.component.ts) component.

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

@Component({
   selector: 'app-expense-entry',
   standalone: true,
   imports: [ExpenseEntryComponent],
   templateUrl: './expense-entry.component.html',
   styleUrl: './expense-entry.component.css'
})
export class ExpenseEntryComponent implements OnInit {
   title: any;
   constructor() {}
   ngOnInit(): void {
      this.title = "Expense Entry"
   }
}

Update template, src/app/expense-entry/expense-entry.component.html with below content.

<h3>{{title}}</h3>
<ul>
   <li><b>Item:</b> Pizza</li>
   <li><b>Amount:</b> 20</li>
   <li><b>Category:</b> Food</li>
   <li><b>Location:</b> Zomato</li>
   <li><b>Spend On:</b> Dec 2024</li>
</ul>

Open src/app/app.component.html and include the newly created component.

<h1>Expense Management Application</h1>
<app-expense-entry></app-expense-entry>
<router-outlet />

Here,

app-expense-entry is the selector value and it can be used as a regular HTML Tag.

At the end, import ExpenseEntryComponent to the app.component.ts file as shown below −

import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { ExpenseEntryComponent } from './expense-entry/expense-entry.component';

@Component({
 selector: 'app-root',
 standalone: true,
 imports: [RouterOutlet, ExpenseEntryComponent],
 templateUrl: './app.component.html',
 styleUrl: './app.component.css'
})
export class AppComponent {
 title = 'expense-manager';
}

Finally, the output of the application is −

component example angular

Component Lifecycle Hook

Angular component goes through a series of stages/events during its existence. The different stages of the Angular Components Lifecycle are creation, change detection, rendering and destruction.

Each phase of the angular component is associated with a lifecycle hook interface which can be implemented to perform arbitrary action in that particular phase. The lifecycle hooks refer to the methods of lifecycle hook interfaces.

Component Interaction

Component interaction is one of the important and necessary features in the context of component based architecture. Angular provides multiple options to pass and receive data between components.

You can share data from parent component to child component as well as, child to parent component. Also, it is possible to share data between any other component within the Angular application.

In Angular, parent and child components interacts through the following ways −

  • @Input decorator
  • @Output decorator
  • local variable
  • @Viewchild decorator
  • Services

Component Styling

Component styling is the process of designing and formatting the visual presentation of views or components. You can use the following ways for styling:

  • Using "styles"
  • Using "styleUrls"
  • Styling through template
  • Using global styles
  • Using CSS preprocessor
  • Customized styles
  • Using custom selectors

Nested Components

Nested components are normal Angular Components with parent-child relations. The parent can access and share data with the child, either partially or fully. The component nested inside another component is called child component. The component containing the child component is called the parent component.

Dynamic Components

Angular allows the component to be dynamically created and loaded at run time at a specific location in the host (another) component.

You can create dynamic components in Angular using the following ways −

  • Using NgComponentOutlet
  • Using ViewContainerRef

Multiple Choice Questions (MCQ) on Angular Components

You have reached the end of this chapter. Now, it's time to check your understanding of the angular component concept. Please try to give correct answers to the questions given below −

Answer : B

Explanation

An Angular Component is responsible for generating views and managing the behavior associated with them.

Q. 2 - Which Angular decorator is used to define a component?

A - @Component

B - @NgModule

C - @Directive

D - @Injectable

Answer : A

Explanation

The @Component decorator is used to define an Angular component, which contains metadata such as the selector, template, and style URLs.

Answer : B

Explanation

The ng generate component component-name command is used to create a new component in an Angular application using Angular CLI.

Advertisements