@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
Component Inputs and Outputs
Input Properties
Receive data from parent components:Output Properties
Emit events to parent components: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 withOnPush 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
- Keep components focused - Single responsibility principle
- Use OnPush when possible for better performance
- Implement lifecycle hooks only when needed
- Clean up in ngOnDestroy - Prevent memory leaks
- Use standalone components for better tree-shaking
- Leverage signals for reactive state management
Next Steps
Templates
Learn template syntax and bindings
Directives
Extend component behavior with directives
