Handling Property Changes Using Decorator - an Alternative to ngOnChanges
Angular 2.0+ provides a beautiful way of communicating with components using Input and Output decorators and lifestyle hooks to perform different tasks.
Join the DZone community and get the full member experience.
Join For FreeAngular (2.0+) provides a beautiful way of communicating with components using @Input and @Output decorators. And, it also provides different lifecycle hooks to perform various tasks at different stages of the component. "ngOnChanges" is also one such lifecycle hooks that let you listen for any property changes and do custom actions or execute business logic. Below is the basic syntax of "ngOnChanges"
x
@Component({
selector: 'app-component',
template: '<div>Say Hello to {{ name }}</div>'
})
class MyComponent implements OnChanges {
// TODO(issue/24571): remove '!'.
@Input() name!: number;
ngOnChanges(changes: SimpleChanges) {
}
}
The problems with "ngOnChanges" are:
- It's an unbrella method which is invoked on every property change
- It is tedious to parse targetted property from "changes" object
- It can easily grow big if there are plenty of properties to watch for.
However, there are alternative and better approaches to listen for property changes than "ngOnChanges"
Alternative #1: Using "setter/getter" for Properties
If you are looking to watch for changes in specific property values, you can define "setter"/"getter" methods for targetted properties and define your business login in those methods. Below is an example of taping property changes using setter/getter method:
xxxxxxxxxx
import { Component, Input } from '@angular/core';
@Component({
selector: 'hello',
template: `<h1>Hello {{name}}!!!</h1><div>Greetings: {{greetings}}</div>`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
private _name: string;
greetings: string;
@Input()
get name() {
return this._name;
}
set name(value: string) {
this._name = value;
this.onNameChange(value);
}
onNameChange(name: string) {
this.greetings = name + '!!!!!';
}
}
However, the component code can grow big if there are good number of properties to watch for. Also, it is redundant effort to write getter/setter syntax and cluttering the component code. That's where the decorators come to rescue.
Alternative #2: Introducing "OnPropertyChange" Decorator
To avoid this redundant effort to writing getter/setter or cryptic ngOnChanges, I implemented a typescript decorator that can set up getter/setter for my and also invoke the given method wheneveer that property is updated. Below is the code for my onPropertyChange decorator.
x
export function OnPropertyChange<T= any>(methodName: string, scope?: any) {
return (target: T, key: keyof T): void => {
const originalDescriptor = Object.getOwnPropertyDescriptor(target, key);
let val;
// Wrap hook methods
Object.defineProperty(target, key, {
set(value) {
const instance = this;
const previousValue = val;
if (previousValue === value) {
return;
}
val = value;
if (originalDescriptor) {
originalDescriptor.set.call(instance, value);
}
if (methodName && val !== previousValue) {
instance[methodName].call(scope || instance, value, previousValue);
}
},
get() {
const instance = this;
if (originalDescriptor) {
return originalDescriptor.get.call(instance);
}
return val;
}
});
};
}
And consuming this decorator in your component is straight forward.
xxxxxxxxxx
import { Component, Input, OnChanges, SimpleChanges, SimpleChange } from '@angular/core';
import { OnPropertyChange } from './property-change.decorator';
@Component({
selector: 'hello-prop-decorator-example',
template: `...`,
styles: [`h1 { font-family: Lato; border-top: 1px solid #CCCCCC;}`]
})
export class HelloPropDecoratorExampleComponent {
public greetings: string = '';
@Input()
@OnPropertyChange('onNameChange')
name: string;
onNameChange(newName: string) {
this.greetings = newName + '!!!!!';
}
}
As you can see, my component is pretty clean and more readable with decorator than the previous two approaches. You can further enhance the decorator to invoke this method only after certain lifecycle hooks are invoked etc.
You can find a working example for this code snippets at https://stackblitz.com/edit/angular-property-changes
Opinions expressed by DZone contributors are their own.
Comments