Constructor
The constructor is a TypeScript feature used to initialize class members. It is called when the component is instantiated. The constructor is called before Angular sets any input properties or runs any lifecycle hooks.
Usage: You typically use the constructor for dependency injection and to initialize class properties. However, you should avoid complex logic or operations that depend on the component's view or input properties.
ngOnInit
ngOnInit is a lifecycle hook provided by Angular that is called after the component's constructor and after Angular has initialized all data-bound properties. It is called once the component is fully initialized, and it is a good place to perform any additional initialization tasks that require access to input properties or the component's view.
Usage: You can use ngOnInit to fetch data from services, set up subscriptions, or perform any other initialization that requires the component to be fully set up.
Difference Between Constructor and ngOnInit.
Feature | constructor() |
ngOnInit() |
---|---|---|
Purpose | Initializes class members and injects dependencies | Used for component initialization logic after inputs are set |
Lifecycle | Runs when the class is instantiated (before Angular binds inputs) | Runs after the constructor, when Angular has fully initialized the component |
Best Use | Dependency injection, initializing simple properties | Fetching data, calling APIs, and logic that depends on @Input() |
Called By | JavaScript engine | Angular framework |
Example Angular Code:
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-example', templateUrl: './example.component.html', }) export class ExampleComponent implements OnInit { data: string; constructor() { // Constructor logic (e.g., dependency injection) console.log('Constructor called'); } ngOnInit() { // Initialization logic that requires the component to be fully set up this.data = 'Hello, World!'; console.log('ngOnInit called'); } }
Summary
- Use a constructor for setting up dependencies and initializing properties.
- Use ngOnInit for any logic that needs Angular to finish setting up the component (like input bindings or DOM access).
✅ Rule of Thumb: “Keep constructor light, move logic to ngOnInit().”
No comments:
Post a Comment