Components Modules · Quick recall Q&A
2 min readQuick recall Q&A
Constructor is for dependency injection and simple initialization. ngOnInit is called after Angular sets up input properties and is the right place for initialization logic, API calls, and subscriptions.
- Component relies only on inputs
- Inputs are immutable
- Component uses observables with async pipe
- You want to manually control change detection
Use OnPush for performance optimization when:
- Unsubscribe from observables
- Detach event handlers
- Clear intervals/timeouts
- Cancel pending HTTP requests
Clean up resources to prevent memory leaks:
- Services with Subject/BehaviorSubject
- State management (NgRx, Akita)
- Route parameters
- Local storage
- Query parameters
Use:
ViewChild queries template of the component itself. ContentChild queries projected content (ng-content). Use ViewChild for internal elements, ContentChild for projected elements.
- Lazy load modules
- TrackBy with ngFor
- Unsubscribe from observables
- Avoid function calls in templates
- Use pure pipes
- Virtual scrolling for large lists
- Use OnPush change detection
imports: Other modules needed by this moduleexports: Make declarations available to other modules
- declarations: Components, directives, pipes that belong to this module
<ng-content> allows parent to inject content into child template. Use select attribute for multiple slots. Useful for creating reusable container components.
Angular 14+ feature that eliminates need for NgModule. Components import dependencies directly. Simpler for small apps and component libraries.
Use ngOnChanges hook which receives SimpleChanges object showing previous and current values of changed inputs.