Introduction
In this article, we are going to see what is ngOninit() method, when and why to use ngOnInit() method.
Prerequisites
- HTML, CSS, and JS
- Basics of TypeScript.
- import { Component, OnInit } from '@angular/core';
- import { Http } from '@angular/http';
-
- @Component({
- selector: 'app-posts',
- templateUrl: './posts.component.html',
- styleUrls: ['./posts.component.css']
- })
- export class PostsComponent implements OnInit {
- posts: any[];
- private url = 'http://jsonplaceholder.typicode.com/posts';
- constructor(private http: Http)
- {
- http.get(this.url)
- .subscribe(response=> {
- console.log(response.json());
- this.posts = response.json();
- });
- }
-
- ngOnInit() {
- }
- }
As a best practice we should have a constructor of very small and light weight. We should not perform expensive operations like calling of server.
Then when can we call it?
Components in Angular have lifecycle hooks. There are special methods that we can add to Angular, and Angular will call these methods at specific times during the lifecycle of the component.
Lifecycle Hooks
When Angular
- Creates a Component
- Renders it
- Creates and renders its children
- Destroys a component
These are lifecycle events. Angular will call specific methods if they are defined. One of its methods is called ngOnInit.
OnInit interface
Defined under @angular/core library,
- Interface OnInit {
- ngOnInit(): void
- }
This interface declares a method called ngOnInit which takes no arguments and returns void. This is the method that Angular calls when it initializes the component.
OnInit is an interface that refers to the lifecycle hook. There are multiple lifecycle hooks in Angular:
- OnInit
- OnChanges
- DoCheck
- AfterContentInit
Each of these interfaces declares a method with the same name prefix with ng . So for OnInit we have a method called ngOnInit.
OnInit
Technically we don’t need to implement OnInit interface on the top as long as we have a method called ngOnInit() defined in our class. Angular will automatically call this when it initializes our component but we use implement OnInt interface to add compile time checking, so when we define implement OnInit interface typescript ensures that we have a method called ngOnInit.
So the lesson is, o not call the http services inside constructors. If you want initialization then do that in ngOnInit method.
EG,
- import { Component, OnInit } from '@angular/core';
- import { Http } from '@angular/http';
-
- @Component({
- selector: 'app-posts',
- templateUrl: './posts.component.html',
- styleUrls: ['./posts.component.css']
- })
- export class PostsComponent implements OnInit {
- posts: any[];
- private url = 'http://jsonplaceholder.typicode.com/posts';
- constructor(private http: Http)
- {
-
- }
-
- ngOnInit() {
- this.http.get(this.url)
- .subscribe(response=> {
- console.log(response.json());
- this.posts = response.json();
- });
- }
- }