Components - Building Blocks
📚 What are Components?
Components are the fundamental building blocks of Angular applications. Each component consists of:
- Class: Contains data and logic (TypeScript)
- Template: Defines the view (HTML)
- Styles: Component-specific CSS
- Metadata: @Component decorator configuration
🎯 Interview Questions
- Q1: What is the difference between a component and a directive?
- A: Components have templates, directives don't. Components are directives with a view.
- Q2: What is ViewEncapsulation?
- A: Controls how styles are scoped. Options: Emulated (default), None, ShadowDom.
- Q3: What is ChangeDetectionStrategy?
- A: Default checks all components, OnPush only checks when inputs change or events occur.
🔧 Live Demo
Component with Signal State
Counter Value: 0
Doubled: 0
💻 Code Example
import { Component, signal, computed, ChangeDetectionStrategy } from '@angular/core';
@Component({
selector: 'app-counter',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<p>Count: {{ count() }}</p>
<p>Doubled: {{ doubled() }}</p>
<button (click)="increment()">+</button>
`
})
export class CounterComponent {
// Signal state
count = signal(0);
// Computed derived state
doubled = computed(() => this.count() * 2);
increment() {
this.count.update(v => v + 1);
}
}