InterviewSolution
Saved Bookmarks
| 1. |
What are lifecycle hooks in Angular? Explain a few lifecycle hooks. |
|
Answer» Every component in Angular has a lifecycle, and different phases it goes through from the time of creation to the time it's destroyed. Angular provides hooks to tap into these phases and trigger changes at specific phases in a lifecycle.
Let’s understand how to use ngOnInit hook, since it’s the most often used hook. If one has to process a lot of data during component creation, it’s better to do it inside ngOnInit hook rather than the constructor: import { Component, OnInit } from '@angular/core';@Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component.css'] }) export class TestComponent implements OnInit { constructor() { } ngOnInit() { this.processData(); } processData(){ // Do something.. } } As you can see we have imported OnInit but we have used ngOnInit function. This principle should be used with the rest of the hooks as well. |
|