Components Modules · Quick recall Q&A

2 min read
Mid-level2 min read
Rapid overview

Quick recall Q&A

Q: What's the difference between constructor and ngOnInit?

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?

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?

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?

Use:

Q: What's the difference between ViewChild and ContentChild?

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?

- Use OnPush change detection

  • imports: Other modules needed by this module
  • exports: Make declarations available to other modules
Q: What's the difference between declarations, imports, and exports in NgModule?

- declarations: Components, directives, pipes that belong to this module

Q: How does content projection work?

<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?

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?

Use ngOnChanges hook which receives SimpleChanges object showing previous and current values of changed inputs.

See also