- Component lifecycle hooks:
Component lifecycle hooks allow you to perform actions at different stages of a component’s lifecycle, such as initialization, rendering, and destruction. Some commonly used lifecycle hooks include ngOnInit
, ngOnChanges
, ngOnDestroy
, etc.
In the component class, you can implement the desired lifecycle hooks and add custom logic. For example:
import { Component, OnInit, OnDestroy } from '@angular/core';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls:
['./my-component.component.css']
})
export class MyComponent implements OnInit, OnDestroy {
ngOnInit() {
console.log('Component initialized');
}
ngOnDestroy() {
console.log('Component destroyed');
}
}
The ngOnChanges
hook is another important lifecycle hook that is called whenever there are changes to the input properties of a component. It provides you with the ability to react to these changes and perform any necessary actions.
In the component class, you can implement the ngOnChanges
hook and define the logic to handle the changes. The hook receives a SimpleChanges
object that contains information about the changes to the input properties.
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnChanges {
@Input() name: string;
ngOnChanges(changes: SimpleChanges) {
// Check if the 'name' input property has changed
if (changes.name) {
console.log('Name changed:', changes.name.currentValue);
}
}
}
In this example, whenever the name
input property changes in the parent component, the ngOnChanges
hook is called in the child component. You can access the new value of the property using changes.name.currentValue
and perform any necessary actions.
The ngOnChanges
hook is particularly useful when you need to react to changes in input properties and update the component’s behavior or state accordingly.
During the component’s lifecycle, Angular will call the corresponding hooks, allowing you to perform tasks like initializing data, subscribing to observables, or cleaning up resources when the component is destroyed.
This covers the detailed explanation and code implementation for Chapter 3: Angular Components.