python ruby-programming-language Smalltalk Vue.js Knockoutjs TypeScript JavaScript, OOPs JavaScript Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 4 Angular 2 AngularJs 1.x NodeJs Perl Programming R Programming RequireJs Rust Programming Backbonejs closure programming language go-programming-language kotlin-programming-language
Angular 2

When will ngInit be called? How would you make use of ngOnInit()?

In Angular 1.x, ngInit is called when template is re-rendered. In other words “ng-init” is called, when I take turns back to a page.

In Angular2, there is no “ng-init” but we can create a ways like this using the directive and ngOnInit class. Angular 2 provides life cycle hook ngOnInit by default.

The ngOnInit is invoked when the component is initialized and invoked only once when the directive is instantiated. It is a best practice to implement these life-cycle interfaces.

Stayed Informed - 13 Best Advantages for Angular 2

According to Angular2 Doc, “The 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.”

For example as,
import { Directive, Input } from '@angular/core';

  selector: '[ngInit]'

class NgInit {
  @Input() ngInit;

  ngOnInit() {
    if(this.ngInit) { this.ngInit(); }

In template as following,
<div *ngIf="Timer.dateTime === currentDateTime">
    <div *ngIf="Timer.checked" [ngInit]="Start"></div>
    <div *ngIf="!Timer.checked" [ngInit]="Stop"></div>

I hope you are enjoying with this post! Please share with you friends!! Thank you!!!

Hi there! Welcome to my blog. My name is Anil Singh. I'm a author of this blog. For more detail about me, kindly refer to this link..
My Blogs - and
My Books - Interview Questions and Answers Books- Get Your Book in 15+ Digital Stores Worldwide..

You Might Also Like Powered by Blogger.
ASK Questions