Angular – TypeScript Constructor versus Angular ngOnInit

angular

Deprecated: get_the_author_email is deprecated since version 2.8.0! Use get_the_author_meta('email') instead. in /home/cloudber/public_html/wp-includes/functions.php on line 4713

TypeScript constructor and Angular ngOnInit look pretty much the same, but they have differences.

1. Injecting and Consuming Service

Use constructor for injecting dependencies into the class. This is because of the execution of constructor always comes before ngOnInit.

app/user/user.service.ts
import {  Injectable  } from '@angular/core';

@Injectable()
export class UserService{
    getUsers(): Array<any>{        
          return [{ name : "Chia Chong"}, { name : "Chia Chuan"},{ name : "Chia Sheng"}];    
    }
}

1. In this example, the UserComponent class does not implement OnInit. A single service is injected into the class throughconstructor.

app/user/user.component.ts (Without OnInit)
import { Component } from '@angular/core';
import { UserService } from './user.service';

@Component({
    selector: 'user-app',
    template: ``,
    providers: [UserService]
})
export class UserComponent{
     users: Array<any>;
     
     constructor(private userService: UserService){};
}

2. Now, import OnInit from @angular/core, then make UserComponent class to implement OnInit.

In this example, the UserComponent class consumes userService in the ngOnInit right after the service is injected via constructor.

This sequence is more appropriate where a service is only be ready for consumption after the service is injected over constructor.

app/user/user.component.ts (With OnInit)
import { Component, OnInit  } from '@angular/core';
import { UserService } from './user.service';

@Component({
    selector: 'user-app',
    template: `
         <ul>
            <li *ngFor="let user of users">{{ user.name }}</li>
         <ul>    
    `,
    providers: [UserService]
})
export class UserComponent implements OnInit{
    users: Array<any>;
    
    constructor(private userService: UserService){};
    
    ngOnInit(): void {
        this.getUsers();
    }
    
    getUsers(): void {         
        this.users = this.userService.getUsers(); 
    }
}

In a nut shell, wire up dependencies via construtor, then do component initialization in ngOnInit.

2. Resolve Binding

Another great example of constructor vs ngOnInit in link-Component resolve binding. The following example demonstrates, binding is resolved in ngOnInit rather than constructor.

parent.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-parent',
  template: `
    <h1>Welcome to Angular World</h1>
    <p>Hello {{name}}</p>
    <app-child [pname]="name"></app-child>
  `
})
export class ParentComponent {
  private name: string = '';

  constructor() {
    this.name = 'CloudBerry';
  }
}
child.component.ts
import { Component, Input, OnInit } from '@angular/core';

@Component({
    selector: 'app-child',
    template: `
     <p>Parent Component Name:{{pname}} </p>
    `
})
export class ChildComponent implements OnInit {
    @Input()
    private pname: string; //parent component name

    constructor() {
        window.console.log('ChildComponent constructor ', this.pname); // Output:undefined
    }

    ngOnInit(): void {
        window.console.log('ChildComponent ngOnInit ', this.pname);
    }
}
Output
ChildComponent constructor  undefined
ChildComponent ngOnInit  CloudBerry

References:
https://angular.io/docs/ts/latest/api/core/index/OnInit-class.html

Author: Wu Chia Chong

My main areas of interest are software architectures and software design methods, patterns, and new trends in software development.

Author: Wu Chia Chong

My main areas of interest are software architectures and software design methods, patterns, and new trends in software development.