Welcome back to our Angular learning journey! In this installment, we’ll explore Angular Components – the fundamental building blocks that make Angular applications modular and maintainable.
What Are Angular Components?
Components are the core UI elements that:
- Control a section of the screen (called a view)
- Consist of:
- A TypeScript class (
component.ts) for logic - An HTML template (
component.html) for layout - Optional CSS styles (
component.css) - A configuration decorator (
@Component)
- A TypeScript class (
Creating Your First Component
Let’s generate a new component using Angular CLI:
ng generate component hello-world # Shorthand: ng g c hello-world
This creates:
src/app/hello-world/ ├── hello-world.component.ts ├── hello-world.component.html ├── hello-world.component.css └── hello-world.component.spec.ts
Understanding the Component Structure
Examine hello-world.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-hello-world',
templateUrl: './hello-world.component.html',
styleUrls: ['./hello-world.component.css']
})
export class HelloWorldComponent {
// Component logic goes here
}
Key parts:
- @Component Decorator: Configures how the component behaves
- Selector: The HTML tag name (
<app-hello-world>) - Template: The associated HTML view
- Styles: Component-specific CSS
Using the Component
Add it to app.component.html:
<h1>My Angular App</h1> <app-hello-world></app-hello-world>
Component Lifecycle Hooks
Angular components have lifecycle events you can tap into:
import { Component, OnInit } from '@angular/core';
export class HelloWorldComponent implements OnInit {
constructor() { }
ngOnInit(): void {
console.log('Component initialized!');
}
}
Common lifecycle hooks:
ngOnInit: After first displayngOnChanges: When input properties changengOnDestroy: Cleanup before destruction
Component Communication
Components often need to share data:
Parent → Child (Input Binding)
// Parent component <app-child [message]="parentMessage"></app-child> // Child component @Input() message: string;
Child → Parent (Output Event)
// Child component
@Output() notify = new EventEmitter<string>();
sendMessage() {
this.notify.emit('Hello from child!');
}
// Parent component
<app-child (notify)="onNotify($event)"></app-child>
Best Practices
- Single Responsibility: Each component should do one thing well
- Smart vs Dumb Components: Separate logic (smart) from presentation (dumb)
- Reusability: Design components to be reusable
- Proper Naming: Use descriptive names (e.g.,Â
user-profile.component.ts)
Hands-On Exercise
- Create aÂ
counter component with:- A count number
- Increment/Decrement buttons
- Reset functionality
- UseÂ
@Input()Â to set an initial value - Emit an event when count reaches 10
What’s Next?
In Part 4, we’ll explore Data Binding in Angular – how to keep your templates and components in sync!
💡 Pro Tip: Experiment with different lifecycle hooks to understand when they trigger.
