Difference between constructor and ngOnInit in angular

Published On: 2021/04/24

Many of the newcomers in angular has confusion regarding the code to be put in the constructor and the code to be put in ngOnInit. A constructor, which is an object oriented concept, will be used to create new objects of a class. On the other hand the method ngOnInit is a lifecycle hook in Angular. This method will be called by angular when a component is initialized.

export class TestComponent implements OnInit {
    constructor() {
        console.log('Called Constructor');
    }
    
    ngOnChanges() {
        console.log('Called ngOnChanges method');
    }

    ngOnInit() {
        console.log('Called ngOnInit method');
    }    

}

When the above code executes, we could find that the method ngOnInit is called after the constructor execution. Keep one thing in mind that the ngOnInit will be called not just after the constructor creation but after first ngOnChanges.

When to use constuctor and when to use ngOnInit - Expalined with example

Let us take an example of constructing a house. Here we need skilled labours like mason, carpenter, electrician, material supplier etc. We depend on these skilled persons to build a house. Once these dependencies are ready we start using them to initialize the items that are required to build the house. In the below code, the supplierService is being used in the ngOnInit to fetch the cement bags so that masons could start their work.

The below code is a kind of psuedo code to explain the difference in usage of constructor and ngOnInit.

export class HouseConstructComponent implements OnInit {
    private woodCount: int;
    private cementBagCount: int;
    private bulbCount: int;

    @Input("plot-area") plotArea: number;

    private cementBags?: CementBag[];

    constructor(private masonService: MasonService, 
                private carpenterService: CarpenterService, 
                private supplierService:SupplierService) {
        this.woodCount = 20;
        this.cementBagCount = 40;
        this.bulbCount = 20;
        console.log('Dependencies are ready to serve');
    }

    ngOnChanges(changes: SimpleChanges) {
        console.log("Plot area is marked");        
    }

    ngOnInit() {
        this.cementBags = supplierService.getCementBags(this.cementBagCount);
        console.log('Got cement bags');
    }
    
}

Conclusion

In this article, we have learnt that when Angular calls ngOnInit it has finished creating a component DOM, injected all required dependencies through constructor and processed input bindings.

comments powered by Disqus