You are on page 1of 14

Hooking into Component Life Cycle

- A component instance has a lifecycle.


- The lifecycle starts when Angular instantiates the
component.
- The first method that executes in a component is
constructor, which is responsible from instantiating the
component.
- The lifecycle continues with Change Detection.
- The lifecycle ends when Angular destroys the
component instance and removes from DOM.
- Component Creates, updates and destroys instances.
- All phases of a component are maintained by a
sequence of events.
- These events are controlled with a set of methods
known as “Hook method”.
- Often known as “Life Cycle Hooks”.
- The lifecycle methods used by component are:
Hook Method Purpose
ngOnChanges() - Angular sets the value
into property.
- Binds the values to any
DOM property.
- It gets notified with the
changes in values by
using “SimpleChanges”
object.
- It gets the previous
value and current value.
- It includes loading
component and handing
any action (event)
performed in
application.
- It loads both child and
parent components.
- It binds their values.
- Manages the property
and event binding in
angular.
ngOnInit() - It will be called after the
first “ngOnChanges()”
- Initialize the directive or
component after
component displays the
properties.
- Initialize memory for
transporting data across
components and bind to
parent and child
properties.
- Memory initialized to
handle value between
interactions.
ngDoCheck() - Called immediately after
“ngOnChanges()” or
every Change detection
and also immediately
after “ngOnInit()” first
run.
- It can detect and act
upon the changes that
Angular can’t or won’t
detect implicitly.
- It is very regular while
using Custom Events
with “@Input() and
@Output().
- Transporting of Data
between components.
ngAfterContentInit() - It is called after
“ngOnInit()”
- Content into the
components view.
(.html)
- It binds the content into
dynamic angular
components like “ng-
container, ng-template”
ngAfterContentChecke - Called after
d() “ngAfterContentInit()”
- It is also called after
every “ngDoCheck()”
- This is responsible for
“Content Projection”
- It is a way to import
HTML content from
outside the component
and insert that content
into component
template at specific
location.
- After binding data to
view on current
component. It brings the
content from external
component or child
component and renders
into current component.
ngAfterViewInit() - Called after
“ngAfterContentChecked()

- Fire up after the
initialization of memory
for component views
and its child view.
- It responds to view
changes.
- It identifies the changes
in parent or child view
and updates the
content.
- Manages Input of data
from parent to child,
output of data from
child to parent.
- Tracking of changes in
data and transporting
the changes to update.
[between parent and
child]
ngAfterViewCheked() - It is called after
“ngAfterViewInit()”
- It renders the final
content into parent and
child views.
ngOnDestroy() - Clean up the memory
before destroying the
component.
- Unsubscribe to methods.
- Detach the event
handling.
- Destroying memory
allocated for
component.
- It is important to handle
memory leaks.

FAQ:
- What is Change Detection?
- What is Content Projection?
- Why to destroy a component?

Change Detection
- It is managed under “ngOnChanges()”.
- Sets the value to property.
- If no value defined into property then no change
detected.
- Binds the value to HTML element property.
- If there is a value defined into property and that is
bound to element property then Change detected.
- Detect the changes in value.
- Update the change to Model.
- “ngModel” with property and event binding [Two-way
binding] is one of the live examples of “Change
Detection”. [(ngModel)]
- Model is “Single-Source-of-Truth”.
- “SimpleChanges” is the base that identifies the changes
by accessing
o CurrentValue
o PreviousValue
- “SimpleChanges” object identified the changes in any
property and update the changes.
- SimpleChanges uses “SimpleChange” base class that
provides the properties
o previousValue:any
o currentValue:any
o firstChange:boolean

Note: Change Detection means either value assigned to


property and value bound to HTML element. It also
identifies the changes in value and updates to model. It is
responsible for “Property Binding and Event Binding”.

Ex:
- Add following components
o ng g c displayvalue
o ng g c sendvalue
- displayvalue.component.ts
import { Component, Input, OnChanges, SimpleChanges
} from '@angular/core';

@Component({
selector: 'app-displayvalue',
templateUrl: './displayvalue.component.html',
styleUrls: ['./displayvalue.component.css']
})
export class DisplayvalueComponent implements
OnChanges {

@Input() public userName;


public previousValue;
public currentValue;
public msg;
constructor() { }

ngOnChanges(changes: SimpleChanges){
for(var property in changes) {
let change = changes[property];
this.currentValue = change.currentValue;
this.previousValue = change.previousValue;
}
if(this.currentValue==this.previousValue){
this.msg = 'No Change Detected';
} else {
this.msg = 'Change Detected';
}
}
}
- Displayvalue.component.html
<div>
<h2>Child Component</h2>
Hello ! {{userName}}
<h2>{{msg}}</h2>
<dl>
<dt>Previous Value</dt>
<dd>{{previousValue}}</dd>
<dt>Current Value</dt>
<dd>{{currentValue}}</dd>
</dl>
</div>
- Sendvalue.component.ts
export class SendvalueComponent {
public userName;
}
- Sendvalue.component.html
<div class="container-fluid">
<h2>Parent Component</h2>
<div>
<label>User Name</label>
<div>
<input [(ngModel)]="userName" type="text">
</div>
</div>
<div>
<app-displayvalue [userName]="userName"></app-
displayvalue>
</div>
</div>

Content Projection
- It is a way to import HTML content from outside the
component and insert that content into component
template at specific location.
- ngAfterContentChecked() is the life cycle hook
responsible for content projection.
- The external templates are access and display at
any specific location by using an object of type
“TemplateRef”.
- A “TemplateRef” object is responsible to
rendering external template into component at
specific location.
- TemplateRef and handle multiple content.
- Which content to display in a view is explicitly
managed by using another decorator
“@ViewChild()”
- It can display one content before change and
another content after change.
@ViewChild
- It is a property decorator.
- It configures a query in view.
- It is responsible for content projection.
- It configures a query based on selector and select
a view to render into the component at specific
location.
- It can project the content explicitly.
- It has two situations to render the content
o Before Change Detection
o After Change Detection
- You can configure the meta data for
“@ViewChild()” by using following properties:
o Selector: It specifies the template name to
render explicitly.
o Read: It is used to read a token explicitly and
render value from token.
o Static: If set to “true” then content will be
projected before change detection. If set to
false then content will be projected after
change detection. Default is false.

Note: You can manage content projection before or


after the change detection.
Ex:
Contentprojection.component.ts
import { Component, OnInit, TemplateRef, ViewChild }
from '@angular/core';

@Component({
selector: 'app-contentprojection',
templateUrl: './contentprojection.component.html',
styleUrls: ['./contentprojection.component.css']
})
export class ContentprojectionComponent implements
OnInit {

public isVisible = false;


public thenBlock: TemplateRef<any> | null = null;

@ViewChild('details', {static: false}) details:


TemplateRef<any> | null;
@ViewChild('preview', {static: false}) preview:
TemplateRef<any> | null;

constructor() { }
ngOnInit(): void {
this.thenBlock = this.preview;
}
public Toggle() {
this.isVisible = true;
this.thenBlock = this.thenBlock==this.preview?
this.details: this.preview;
}
}
Contentprojection.component.html
<div class="container-fluid">
<h2>Product Details</h2>
<div class="card">
<div class="card-header">
<button (click)="Toggle()" class="btn btn-primary
btn-block">Details / Preview</button>
</div>
<div class="card-body">
<div *ngIf="isVisible; then thenBlock else elseBlock
"></div>
<ng-template #details>
<table class="table table-hover">
<tr>
<td>Name</td>
<td>Nike Casuals</td>
</tr>
<tr>
<td>Price</td>
<td>5600.53</td>
</tr>
<tr>
<td>Code</td>
<td>#0101NIKE</td>
</tr>
</table>
</ng-template>
<ng-template #preview>
<img src="assets/shoe.jpg" width="200"
height="200">
</ng-template>
<ng-template #elseBlock>
<h2>Click Preview / Details</h2>
</ng-template>
</div>
</div>
</div>
Angular Pipe, Services, Provides

You might also like