Angular Components
Angular is a component-based framework, meaning every part of your application (header, footer, form, button, page) is built as a component. Each component contains HTML (template), CSS (styles), and TypeScript (logic).
1. Creating a Component
Use Angular CLI to generate a component quickly:
ng generate component home
# or
ng g c home
This creates:
home/
├── home.component.ts → Component logic
├── home.component.html → Template (UI)
├── home.component.css → Styling
├── home.component.spec.ts → Testing file
2. Component Decorator
Every component has an @Component decorator, which tells Angular how to handle it.
import { Component } from '@angular/core';
@Component({
selector: 'app-home', // HTML tag to use this component
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent {
}
3. Component Structure
A component has three main parts:
- Template (HTML) – What the user sees
- Styles (CSS/SCSS) – How it looks
- Class (TypeScript) – Logic and data
Example:
home.component.html
<h2>{{ title }}</h2>
home.component.ts
title = "Welcome to Angular Components!";
4. Data Binding
Angular provides four ways to bind data between the component class and template.
- Interpolation ( {{ }} )
- Displays data in the template:
<p>Hello {{ userName }}</p>
userName = "Chinmaya";
- Property Binding ( [ ] )
- Binds values to HTML element properties:
<img [src]="profileImage">
profileImage = "assets/photo.png";
- Event Binding ( ( ) )
- Handles events like click, input, keypress:
<button (click)="showMessage()">Click Me</button>
showMessage() {
alert("Button clicked!");
}
- Two-way Binding ( [(ngModel)] )
- Used in forms to bind input values. Requires
FormsModuleimported in your module:
import { FormsModule } from '@angular/forms';
Example:
<input [(ngModel)]="fullName" placeholder="Enter name">
<p>You typed: {{ fullName }}</p>
fullName = '';
5. Component Lifecycle Hooks
Angular calls certain methods automatically at specific stages of a component’s life.
Most important hooks:
ngOnInit()– Runs after the component loads (used for API calls)ngOnDestroy()– Runs before the component is destroyed (used to unsubscribe from observables)ngOnChanges()– Runs when input properties changengAfterViewInit()– Runs after the component’s view is initialized
Example:
import { Component, OnInit, OnDestroy } from '@angular/core';
@Component({
selector: 'app-demo',
templateUrl: './demo.component.html'
})
export class DemoComponent implements OnInit, OnDestroy {
ngOnInit() {
console.log('Component initialized');
}
ngOnDestroy() {
console.log('Component destroyed');
}
}
Summary
- Components are the building blocks of Angular
- Use CLI to create components quickly
@Componentdecorator defines selector, template, and styles- Data binding connects templates and logic: interpolation, property, event, two-way
- Lifecycle hooks help manage initialization and cleanup