Angular Components
Angular Components
Creating Components
Components are the building blocks of every Angular application. Each component represents a specific part of the user interface and contains its own logic, template, and styles. By dividing an application into multiple reusable components, Angular makes applications easier to develop, maintain, and scale.
Angular CLI provides a simple command to generate a new component automatically.
Run the following command:
ng generate component greeting
Or use the shorthand version:
ng g c greeting

After the command executes successfully, Angular automatically generates the following files:
- greeting.component.ts – Contains the component's TypeScript logic.
- greeting.component.html – Defines the component's HTML template.
- greeting.component.css – Stores the component's styles.
- greeting.component.spec.ts – Contains unit tests for the component.

Component Templates
A component template defines what users see in the browser. Angular connects the component's TypeScript code with its HTML template, allowing data to be displayed dynamically.
The following example creates a simple greeting component.
greeting.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-greeting',
templateUrl: './greeting.component.html',
styleUrls: ['./greeting.component.css']
})
export class GreetingComponent {
name: string = 'Angular Learner';
}
greeting.component.html
<div class="greeting-card">
<h2>Hello, {{ name }}! 👋</h2>
<p>Welcome to Angular!</p>
</div>
To display this component inside another component, add its selector to the parent template.
<app-greeting></app-greeting>

Component Lifecycle Basics
Every Angular component goes through a lifecycle from the moment it is created until it is destroyed. Angular provides lifecycle hooks that allow developers to execute code at different stages of a component's life.
Some of the most commonly used lifecycle hooks include:
- ngOnInit() – Runs once after the component is initialized. It is commonly used to fetch data from APIs or perform initialization tasks.
- ngOnChanges() – Executes whenever an @Input() property receives a new value from its parent component.
- ngOnDestroy() – Runs just before the component is removed from the page. It is typically used to unsubscribe from Observables, stop timers, or release resources.
The following example demonstrates the ngOnInit() lifecycle hook.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-greeting',
templateUrl: './greeting.component.html'
})
export class GreetingComponent implements OnInit {
courses: string[] = [];
ngOnInit(): void {
// Runs once when the component loads
this.courses = ['Angular', 'React', 'Python'];
}
}










