Components Modules · Quick recall Q&A
2 min readRapid overview
Quick recall Q&A
Q: What's the difference between constructor and ngOnInit? 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
Q: When do you use OnPush change detection? A: Use OnPush for performance optimization when:
- Unsubscribe from observables
- Detach event handlers
- Clear intervals/timeouts
- Cancel pending HTTP requests
Q: What's the purpose of ngOnDestroy? A: Clean up resources to prevent memory leaks:
- Services with Subject/BehaviorSubject
- State management (NgRx, Akita)
- Route parameters
- Local storage
- Query parameters
Q: How do you share data between unrelated components? A: Use:
Q: What's the difference between ViewChild and ContentChild? A:
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
Q: How do you optimize Angular performance? A: - Use OnPush change detection
imports: Other modules needed by this moduleexports: Make declarations available to other modules
Q: What's the difference between declarations, imports, and exports in NgModule? A: -
declarations: Components, directives, pipes that belong to this moduleQ: How does content projection work? A:
<ng-content> allows parent to inject content into child template. Use select attribute for multiple slots. Useful for creating reusable container components.Q: What are standalone components? A: Angular 14+ feature that eliminates need for NgModule. Components import dependencies directly. Simpler for small apps and component libraries.
Q: How do you detect changes in input properties? A: Use
ngOnChanges hook which receives SimpleChanges object showing previous and current values of changed inputs.