Angular Component Lifecycle Hooks

Level : Intermediate
Mentor: Shailendra Chauhan
Duration : 00:04:30

ngOnChanges

This hook is triggered when the input properties of a component change.

Example

@Input() inputValue: string;
ngOnChanges(changes: SimpleChanges) {
  if (changes.inputValue) {
    console.log('Input value changed to:', changes.inputValue.currentValue);
  }
}   

ngOnInit

This hook is called once after input values are set and is used for initializing data.

Example

ngOnInit() {
  this.initializeData();
}

ngOnDestroy

This hook is called before a component is destroyed, allowing for resource cleanup.

Example

ngOnDestroy() {
  this.unsubscribeFromObservable();
}

ngDoCheck

This hook is called during each change detection cycle and can be used to manually check for changes.

Example

ngDoCheck() {
  if (this.shouldUpdate) {
    this.updateData();
  }
} 

ngAfterContentInit

This hook is triggered after content projection into the component's view.

Example

ngAfterContentInit() {
  console.log('Content projected and initialized');
}

ngAfterContentChecked

This hook is called after each change detection cycle to check content changes.

Example

ngAfterContentChecked() {
  console.log('Content checked for changes');
}

ngAfterViewInit

This hook is called when the component's view has been fully initialized.

Example

ngAfterViewInit() {
  console.log('View initialized');
}

ngAfterViewChecked

This hook is called after each change detection cycle for checking view changes.

Example

ngAfterViewChecked() {
  console.log('View checked for changes');
}

<input [val]="name">

Binds the value of the name property to the val property of the input element.

Example

<input [value]="name">

<div [attr.role]="myAriaRole">

Binds the value of the myAriaRole property to the role attribute of the <div> element.

Example

<div [attr.role]="myAriaRole">...</div>

<div [class.extra]="isADelight">

Binds the truthiness of the isADelight property to the presence of the CSS class extra on the <div> element.

Example

<div [class.extra]="isADelight">...</div>

<div [style.height.px]="myHeight">

Binds the value of the myHeight property to the height style property of the <div> element.

Example

<div [style.height.px]="myHeight">...</div>
Self-paced Membership
  • 24+ Video Courses
  • 825+ Hands-On Labs
  • 400+ Quick Notes
  • 125+ Skill Tests
  • 10+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Still have some questions? Let's discuss.
CONTACT US
Accept cookies & close this