OnChanges - a change has occurred

This hook is used in the following way:

export class ExampleComponent implements OnChanges {
ngOnChanges(changes: SimpleChanges) { }
}

Note how our method takes an input parameter changes. This is an object with all properties that changed as keys on the changes object. Each key points to an object with the previous value and the current value, like so:

{
'prop' : { currentValue : 11, previousValue : 10 }
// below is the remaining changed properties
}

The preceding code assumes we have a class with a prop field, like so:

export class ExampleComponent {
prop: string;
}

So, what causes things to change? Well, it's a change in the binding, that is, we have the @Input property set up, like so:

export class TodoComponent implements OnChanges {
@Input() item;

ngOnChanges(changes: SimpleChanges) {
for (let change in changes) {
console.log(`
'${change}' changed from
'
${changes[change].previousValue}' to
'
${changes[change].currentValue}'
`
)
}
}
}

A little heads up worth noting here is that what we are tracking are reference changes, not property changes on an object. If, for example, we have the following code:

<todo [item]="todoItem">

And the name property on the todoItem changed so that todoItem.name is code instead of coding, this would not lead to a change being reported. However, if the whole item is replaced, as in the following code:

this.todoItem = { ...this.todoItem, { name : 'coding' });

Then this would lead to a change event being emitted as the todoItem now points to a completely new reference. I hope this clears it up a bit.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset