FSD-II Practical 3
3.Create a custom life-cycle hook for logging
component life-cycle events
- Define a
custom life-cycle hook named `LogLifecycle` that logs component initialization,
destruction, and changes in input properties.
- Implement the custom hook in a sample component.
- Test the
behavior by adding the component to a parent component and observing the logs.
1. ng
new practical3
2. cd
practical3
3. ng
generate service log-lifecycle
4.
open the file
log-lifecycle.service.ts
import
{ Injectable, OnInit,
OnDestroy, OnChanges,
SimpleChanges } from
'@angular/core';
@Injectable({
providedIn:
'root'
})
export
class LogLifecycle
implements OnInit,
OnDestroy, OnChanges
{
constructor()
{
console.log(`${this.constructor.name}
- Constructor called`);
}
ngOnInit():
void {
console.log(`${this.constructor.name}
- Initialized`);
}
ngOnDestroy():
void {
console.log(`${this.constructor.name}
- Destroyed`);
}
ngOnChanges(changes:
SimpleChanges):
void {
console.log(`${this.constructor.name}
- Input properties changed:`, changes);
}
}
5.
create sample component
ng generate component sample
6.
open sample.component.ts
import
{ Component, Input,
OnChanges, SimpleChanges
} from '@angular/core';
import
{ LogLifecycle } from
'../log-lifecycle.service';
@Component({
selector:
'app-sample',
template:
`
<div>
<h2>Sample
Component</h2>
<p>Current
Value: {{ value }}</p>
<button
(click)="changeValue()">Change Value</button>
</div>
`
})
export
class SampleComponent
extends LogLifecycle
implements OnChanges
{
@Input()
value:
number =
0;
changeValue()
{
this.value
= Math.floor(Math.random()
* 100);
// Randomize value
}
//
Use 'override' because this method overrides the base class method
override
ngOnChanges(changes:
SimpleChanges):
void {
super.ngOnChanges(changes);
// Call the base class method
}
}
7.open app.module.ts as parent component
import
{ Component } from
'@angular/core';
@Component({
selector:
'app-root',
template:
`
<div>
<h1>Parent
Component</h1>
<app-sample
[value]="value"></app-sample>
<button
(click)="increaseValue()">Increase Value</button>
</div>
`
})
export
class AppComponent
{
value:
number =
0;
increaseValue()
{
this.value++;
}
}
8.Run on terminal
ng serve

Comments
Post a Comment