Job Interview Questions - Angular
Table of Content
- [[#What is the difference between a service provided in the root injector versus one provided in a specific component or module?]]
- [[#What is the difference between ngOnInit and constructor in a component, and when should you use one over the other?]]
- [[#What is the difference between ViewChild and ContentChild decorators, and when would you use each one?]]
What is the difference between a service provided in the root injector versus one provided in a specific component or module?
- when service is provided in root, it becomes a singleton and is available throughout the entire application. This means there's only one instance of the service, and any component that injects it will get the same instance.
- if a service is provided in a specific module or component, it will have a scoped instance. This means that each module or component that provides it will get its own instance, which helps in isolating functionality and state.
This approach helps manage dependencies more effectively and keeps your application modular.
What is the difference between ngOnInit and constructor in a component, and when should you use one over the other?
- The constructor is a standard TypeScript feature and is called when the component instance is created. It's mainly used for simple initialisations and injecting dependencies.
- The ngOnInit lifecycle hook, is called after Angular has initialised all data-bound properties of the component. This makes it the ideal place to perform any additional initialisation that depends on input properties.
So in short, use constructor for basic setup and dependency injection, and use ngOnInit for any logic that needs to happen after component's inputs are set.
What is the difference between ViewChild and ContentChild decorators, and when would you use each one?
- ViewChild is used to access elements, directives, or components that are part of the component's own template. Essentially, it's for querying the view that the component renders.
- ContentChild is used to access elements, directives, or components that are projected into the component's template from its parent. This is often used with content projection, like when you're using
<ng-content>
to pass content into the component.
In summary, you'd use ViewChild for elements inside your own template, and ContentChild for elements that come from outside, via content projection.