Skip to main content
Components are the fundamental UI building blocks of Angular applications. Each component consists of a TypeScript class decorated with @Component, an HTML template, and optional CSS styles.

The @Component Decorator

The @Component decorator marks a class as an Angular component and provides configuration metadata:

Component Metadata

All components are standalone by default in modern Angular. Set standalone: false only if you need to use NgModules.

Essential Properties

Component Lifecycle

Angular components have a well-defined lifecycle managed by Angular. Implement lifecycle hook interfaces to tap into key moments:
1

Constructor

Called when the component class is instantiated
2

ngOnInit

Called once after the first ngOnChanges
3

ngOnChanges

Called when input properties change
4

ngDoCheck

Called during every change detection run
5

ngAfterContentInit

Called after content projection is initialized
6

ngAfterContentChecked

Called after projected content is checked
7

ngAfterViewInit

Called after component’s view is initialized
8

ngAfterViewChecked

Called after component’s view is checked
9

ngOnDestroy

Called before the component is destroyed

Lifecycle Example

Always clean up resources like subscriptions, timers, and event listeners in ngOnDestroy to prevent memory leaks.

Component Inputs and Outputs

Input Properties

Receive data from parent components:
Usage in parent template:

Output Properties

Emit events to parent components:
Parent component usage:

View Encapsulation

Control how component styles are scoped:

Emulated

Scopes styles to component (default)

None

Styles apply globally

ShadowDom

Uses native Shadow DOM

Change Detection Strategy

Optimize performance with OnPush change detection:
OnPush only checks the component when:
  • Input references change
  • Events are triggered from the component or its children
  • Observables emit new values with the async pipe
  • Manually triggered with ChangeDetectorRef.markForCheck()

Host Element Binding

Bind to the component’s host element:

Best Practices

  1. Keep components focused - Single responsibility principle
  2. Use OnPush when possible for better performance
  3. Implement lifecycle hooks only when needed
  4. Clean up in ngOnDestroy - Prevent memory leaks
  5. Use standalone components for better tree-shaking
  6. Leverage signals for reactive state management

Next Steps

Templates

Learn template syntax and bindings

Directives

Extend component behavior with directives