Skip to main content

Posts

Showing posts with the label Angular 2 Component Constructor vs. OnInit event

Angular 2  Component Lifecycle Hooks [Examples Also]

The common questions ask bye most of Angular 2 lovers, “ Could anyone tell me about the usage of ngOnInit if we already have a constructor? ” but Angular 2 provides life cycle hook ngOnInit by default. Angular 2 Components and Directives has multiple life-time hooks where we custom logic can be executed. Stayed Informed - What Are Components in Angular 5,4 and 2? Angular 2 Constructors :- The constructor is a default method runs when component is being constructed. The constructor is a typescript feature and it is used only for a class instantiations and nothing to do with Angular 2. The constructor called first time before the ngOnInit(). Example as , import {Component} from 'angular2/core' ; import {UserService} from './userService' ; @Component ({ selector: ‘ list - user ’ , template: `<ul><li *ngFor="#user of users">{{user.name}}</li></ul>` }) class App_Component { users:...

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' ; @ Directive({ selector : '[ngInit]' }) class NgInit { @ Input() ngInit; ngOnInit() {...

Modern browsers are supported in Angular 2?

All the  Angular 2 framework  code is already being written in ECMAScript 6. The set of modern browsers are 1.         Chrome 2.         Firefox 3.         Opera 4.         Safari 5.         IE version10 and 11. On mobiles, it is supporting to the list of Chrome on Android, iOS 6+, Windows Phone 8+ and Fire-Fox mobile and also trying to support to older versions of Android.

Angular 2 Component Constructor vs. OnInit event

The constructor is a typescript feature. The constructor is only related to class instantiation and it’s nothing to do with Angular 2 and it is use to some initialization processing with respect to class hierarchies for the newly created instance. The ngOnInit event is an Angular 2 life-cycle event/ method that are called after the first ngOnChanges. The ngOnInit method is use to parameters defined with @Input otherwise the constructor is  OK .