How does a component receive dependencies through the constructor?
In Angular, a component receives dependencies through Dependency Injection (DI), by passing them into the class constructor.
How it works
- Parameters with the types of the services the component needs are added to the component's constructor.
- Angular checks the injector (module or component), looks for the matching service, and creates an instance of it (or takes an existing one).
- After that, the service becomes available in the component through the property defined in the constructor.
Example:
typescript
import { Component } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-example',
template: `<p>{{ data }}</p>`
})
export class ExampleComponent {
data: string;
constructor(private dataService: DataService) {
this.data = this.dataService.getData();
}
}Conclusion: Angular automatically creates and injects service instances through the constructor, freeing the developer from manually creating dependencies.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.