educative.io

Educative

What does OnInit do and how it works in AngularJS?

Hi, I am on the Path of becoming Angular JS Developer. And have questions for module 1 ‘getting started with Angular’, ‘service’ section. And I have questions about the ‘OnInit’ and ‘ngOnInit’. What do they do, and how do we use them?

  1. export class <class_name> {} usually export the class_name class and made it available for other components. Why do we implements OnInit here? What does it do?

  2. ngOnInit. Some tutorial mentioned it is to initiate data for directive. How is it different from constructor? What data are we initiated ,what the data is used for? And when will they be initiated? Will it get initiated when we execute the ‘‘app-root’’ in HTML?

    import { Component, OnInit } from ‘@angular/core’;
    import { DemoService } from ‘./demo.service’;

@Component({
selector: ‘app-root’,
templateUrl: ‘./app.component.html’,
styleUrls: [’./app.component.css’]
})
export class AppComponent implements OnInit {
title = ‘angular-architecture’;
constructor(public demoService: DemoService) {}

ngOnInit(): void {
this.demoService.printHello();
}
}

@chao_ren

it is is a life cycle hook called by Angular to indicate that Angular is done creating the component.

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

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

then to make use of the method OnInit, we have to implement the class like this:

export class App implements OnInit {
  constructor() {
     // Called first time before the ngOnInit()
  }

  ngOnInit() {
     // Called after the constructor and called  after the first ngOnChanges() 
  }
}

Implement this interface to execute custom initialization logic after your directive’s data-bound properties have been initialized. ngOnInit is called right after the directive’s data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated.