In Angular, both the constructor() and ngOnInit() are used during the component's lifecycle, but they serve different purposes.
Constructor:
The constructor() is a TypeScript feature and is called when the class is instantiated. In Angular, it is mainly used for dependency injection and basic setup that does not depend on Angular bindings.
Runs before Angular initializes the component’s inputs (@Input())
.
Used for injecting services or initializing class members.
constructor(private userService: UserService) { // Dependency injection here }
ngOnInit:
The ngOnInit() is an Angular lifecycle hook that runs after the constructor and after Angular has set the component’s @Input() properties.
Ideal for initialization logic, such as:
Fetching data from APIs
Accessing @Input() values
Subscribing to Observables
ngOnInit(): void { // Initialization logic here console.log(this.myInput); // @Input() is now available for us }
For reference: