Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why it is important to import OnInit

Tags:

angular

Without importing OnInit and implements

ngOnInit(){
  this.recipies=this.recipeService.getRecipies();
} 

This is still working fine without any complain so why should i use like :

import { Component,EventEmitter,Output , OnInit } from '@angular/core';

export class RecipiesListComponent implements OnInit{}
like image 247
Ashutosh Jha Avatar asked Nov 23 '16 05:11

Ashutosh Jha


People also ask

What is the purpose of ngOnInit?

ngOnInit() is a place to put the code that we need to execute at very first as soon as the class is instantiated.

Do I need to implement OnInit?

We import OnInit in order to use it, implementing OnInit is not mandatory but considered good practice): import {Component, OnInit} from '@angular/core'; We use ngOnInit to do something after the component has been created. for example you can set variables here, call methods etc.

What is use of OnInit in Angular?

A callback method that is invoked immediately after the default change detector has checked the directive's data-bound properties for the first time, and before any of the view or content children have been checked. It is invoked only once when the directive is instantiated.

Why we use ngOnInit instead of constructor?

The constructor() should only be used to initialize class members but shouldn't do actual “work”. So we should use constructor() to set up Dependency Injection, Initialization of class fields, etc. ngOnInit() is a better place to write “actual work code” that we need to execute as soon as the class is instantiated.


2 Answers

Interface are optional as per the angular documentation so you can use it without importing and implementing it.

Angular instead inspects directive and component classes and calls the hook methods if they are defined but it's good practice to add interfaces to TypeScript directive classes in order to benefit from strong typing and editor tooling.

like image 66
ranakrunal9 Avatar answered Oct 04 '22 16:10

ranakrunal9


We have to import OnInit in order to use like this (actually implementing OnInit is not mandatory but considered good practice).

import {Component, OnInit} from 'angular2/core';

Check this Link. Hope you got your answer.

like image 30
Avnesh Shakya Avatar answered Oct 04 '22 15:10

Avnesh Shakya