# constructor vs ngOnInit in Angular

Source: https://tpiros.dev/blog/constructor-vs-ngoninit-in-angular

If you've looked at an Angular2+ component, you've seen both `constructor()` and `ngOnInit()`. Let's pull apart the differences and understand why they both exist.

# Example code

Here's what a freshly generated component from the Angular CLI looks like (you can create one with `ng generate component`):

```typescript

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css'],
})

  constructor() {}

  ngOnInit() {}
}
```

# The constructor

The `constructor()` has nothing to do with Angular. TypeScript (and ES2015 JavaScript) supports classes, and classes have constructors.

The JavaScript engine invokes it. Angular doesn't.

# ngOnInit

`ngOnInit()` is one of Angular's [lifecycle hooks](https://angular.io/guide/lifecycle-hooks). A lifecycle hook lets you tap into different stages of a component's life. Angular calls `ngOnInit()` after it's finished creating the component.

# When to use constructor and ngOnInit?

Now you can see how they're different, and each fits a different job.

Here's the rule of thumb: use `constructor()` for dependency injection. Wire up the dependencies your component needs.

```typescript

// ...
constructor(private http: HttpClient) { }
```

`ngOnInit` gets called after Angular has created the component, loaded its dependencies, placed it in the DOM, and processed all input bindings. That means input values are accessible inside `ngOnInit` but _not_ inside the constructor:

```typescript
// given that the component is called via: <app-my-component [user]="user"></app-my-component>

  @Input()
  user: any;
  constructor() {
    console.log(this.user); // undefined
  }

  ngOnInit() {
    console.log(this.user); // { username: "John", age: 33 }
  }
}
```
