The ngDoCheck lifecycle hook
gets executed when Angular runs the change detection process. ngOnChanges also gets executed when
changes are detected the difference is that ngOnChanges() detects changes for those properties which are passed
by value. ngDoCheck() detects
changes for those properties also which are passed by reference such as arrays.
For performance reasons OnChanges does not fire when the input property is an
array/object, in these cases we can use ngDoCheck to perform our own custom
change detection.
Let us see how this works with a simple example. We will extend the
example which we used for ngOnChanges,
we will add one more @Input property
to the child component, this time we will add an object instead of a string so
that we can see that ngDoCheck gets
triggered but not ngOnChanges when the object is changed.
User object class
export class User {
name: string;
age: number;
phone: string;
}
Child component
import { Component, OnInit, OnChanges, SimpleChanges, DoCheck, Input } from '@angular/core';
Child component
import { Component, OnInit, OnChanges, SimpleChanges, DoCheck, Input } from '@angular/core';
import {User} from '../user';
@Component({
selector: 'app-child',
templateUrl:
'./child.component.html',
styleUrls:
['./child.component.css']
})
export class ChildComponent implements OnInit, OnChanges, DoCheck {
@Input() Message: string
@Input() user: User;
constructor() { }
ngOnInit() {
}
ngOnChanges(changes:
SimpleChanges) {
console.log('Triggering
ngOnChanges');
console.log(JSON.stringify(changes));
}
ngDoCheck() {
console.log('Triggering ngDoCheck');
}
}
Parent component
import { Component, OnInit } from '@angular/core';
Parent component
import { Component, OnInit } from '@angular/core';
import {User} from './user';
@Component({
selector: 'app-root',
templateUrl:
'./app.component.html',
styleUrls:
['./app.component.css']
})
export class AppComponent implements OnInit {
message: string;
user: User = new User();
constructor() { }
ngOnInit() {
this.message = 'Hello from
Parent.'
this.user.name = 'Hello User'
}
clickHandler() {
//this.message = 'Update from
Parent.';
this.user.name = 'Hello updated User';
}
}
Parent component template
<div>
Parent component template
<div>
<app-child [Message] =
"message" [user] = "user"></app-child>
<input
type="button" (click)='clickHandler()' value="Change
Message">
</div>On click of the button in the parent component we change the name property of the user object, notice that the message from ngDoCheck gets printed in the console and the message from ngOnChanges does not get printed in the console since this event is not triggered.
Final ouput
No comments:
Post a Comment