Component Anatomy
- Angular components are the fundamental building blocks of Angular applications.
- Component’s structure provides a clean separation of concerns while keeping all component parts tightly integrated.
Core Files Structure
Section titled “Core Files Structure”component-name/├── component-name.component.ts // Logic & Class├── component-name.component.html // Template├── component-name.component.css // Styles└── component-name.component.spec.ts // Tests@Component Decorator Properties:
Section titled “@Component Decorator Properties:”selector: Custom HTML tag nametemplateUrl/template: HTML contentstyleUrls/styles: CSS stylesstandalone:truefor standalone components (modern approach)imports: Other components/directives needed
Modern Angular 19+ Features:
Section titled “Modern Angular 19+ Features:”- Standalone Components (recommended)
- Signals for reactive state management
- New Control Flow in templates
Standalone Component Example:
Section titled “Standalone Component Example:”@Component({ selector: "app-standalone", standalone: true, imports: [CommonModule, RouterLink], template: ` <h1>Standalone Component</h1> <a routerLink="/home">Home</a> `,})export class StandaloneComponent { // Uses signals for state count = signal(0);
increment() { this.count.update((v) => v + 1); }}Component Lifecycle (Common Hooks)
Section titled “Component Lifecycle (Common Hooks)”ngOnInit()- InitializationngOnDestroy()- CleanupngOnChanges()- Input changes
Best Practices
Section titled “Best Practices”- Use standalone components for new projects
- Use signals (
signal(),computed(),effect()) for state - Keep components focused and single-purpose
- Use the new control flow (
@if,@for) in templates