Angular — Components
Basic Component
// header.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent {
title = 'My App';
}
Component with Inputs
// product.component.ts
@Component({
selector: 'app-product',
template: `
<h2>{{product.name}}</h2>
<p>{{product.price | currency}}</p>
`
})
export class ProductComponent {
@Input() product: any;
}
Component with Outputs
// child.component.ts
@Component({
selector: 'app-child',
template: `<button (click)="sendMessage()">Send</button>`
})
export class ChildComponent {
@Output() messageEvent = new EventEmitter<string>();
sendMessage() {
this.messageEvent.emit('Hello from child!');
}
}
Lifecycle Hooks
| Hook | Description |
|---|---|
| ngOnInit | After data-bound inputs |
| ngOnDestroy | Before destroying |
| ngAfterViewInit | After view initialized |
| ngDoCheck | Custom change detection |
export class MyComponent implements OnInit, OnDestroy {
ngOnInit() {
console.log('Component initialized');
}
ngOnDestroy() {
console.log('Component destroyed');
}
}
Mini Practice
- Create a component
- Pass data with @Input
- Emit events with @Output
- Use lifecycle hooks
Up Next
Continue with Class Components — component class patterns.
Related Topics
Frequently Asked Questions about Components
What is Components in Angular?
Components is a fundamental concept in Angular. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Components?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Components.
Why is Components important in Angular?
Components is essential for Angular development. Understanding this concept will help you write better code and solve real-world problems more effectively.