Angular Components
Components are the basic building blocks of an Angular application. A component controls a specific part of the user interface and contains the logic, template and styling required for that part.
What is an Angular Component?
An Angular component is a TypeScript class connected to an HTML template. It can also have styles that control the appearance of the component.
Components help developers divide a large application into smaller, manageable and reusable parts.
Basic Structure of a Component
TypeScript
Contains component logic, properties and methods.
HTML Template
Defines what the user sees on the screen.
CSS
Defines the appearance and styling of the component.
Angular Component
Complete reusable UI component.
Simple Component Example
Let's create a simple Student component that displays the name of a student.
import { Component } from '@angular/core';
@Component({
selector: 'app-student',
templateUrl: './student.component.html'
})
export class StudentComponent {
studentName = 'Sam';
}
The component template can display the student name using Angular interpolation.
<h2>Student Details</h2>
<p>
Student Name: {{ studentName }}
</p>
Expected Output
Student Details
Student Name: Sam
@Component Decorator
The @Component decorator tells Angular that a TypeScript class should be treated as a component.
@Component({
selector: 'app-student',
templateUrl: './student.component.html'
})
Component Metadata
Metadata inside the @Component decorator tells Angular how the component should behave and where its template is located.
Component Selector
The selector defines how the component is placed inside another Angular template.
@Component({
selector: 'app-student'
})
The component can then be used in an HTML template like this:
<app-student></app-student>
Component Tree
Angular applications can contain many components. These components can be organized into parent and child components.
Responsibilities of a Component
User Interface
Displays the required part of the application.
Application Logic
Contains TypeScript properties and methods.
User Interaction
Handles user actions and events.
Data Display
Displays application data in the template.
Benefits of Angular Components
Divide a large application into smaller sections.
Make application code easier to maintain.
Create reusable user interface elements.
Improve application organization.
Complete Component Flow
Summary
Angular components are the basic building blocks of Angular applications.
A component contains TypeScript logic and an HTML template, along with optional styling.
Components make Angular applications modular, reusable and easier to maintain.