DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Comprehensive Guide to Property-Based Testing in Go: Principles and Implementation
  • Implement Hibernate Second-Level Cache With NCache
  • Modify JSON Data in Postgres and Hibernate 6
  • Top 10 C# Keywords and Features

Trending

  • The Repo Tracker: Automating My Daily GitHub Catch-Up
  • From ETL to Lakeflow: Shifting to a Declarative Data Paradigm
  • Why Your Test Automation Is Always Behind the Code And the Architecture That Fixes It
  • How to Format Articles for DZone

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.

By 
Ashish Patel user avatar
Ashish Patel
·
Jul. 02, 20 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
8.1K Views

Join the DZone community and get the full member experience.

Join For Free

Angular (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"

TypeScript
 




x


 
1
@Component({
2
  selector: 'app-component',
3
  template: '<div>Say Hello to {{ name }}</div>'
4
})
5
class MyComponent implements OnChanges {
6
  // TODO(issue/24571): remove '!'.
7
  @Input() name!: number;
8

          
9
  ngOnChanges(changes: SimpleChanges) {
10
    
11
  }
12
}


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:

TypeScript
 




xxxxxxxxxx
1
25


 
1
import { Component, Input } from '@angular/core';
2

          
3
@Component({
4
  selector: 'hello',
5
  template: `<h1>Hello {{name}}!!!</h1><div>Greetings: {{greetings}}</div>`,
6
  styles: [`h1 { font-family: Lato; }`]
7
})
8
export class HelloComponent  {
9
  private _name: string;
10

          
11
  greetings: string;
12

          
13
  @Input() 
14
  get name() {
15
    return this._name;
16
  }
17
  set name(value: string) {
18
    this._name = value;
19
    this.onNameChange(value);
20
  }
21

          
22
  onNameChange(name: string) {
23
    this.greetings = name + '!!!!!';
24
  }
25
}



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.

JavaScript
 




x


 
1
export function OnPropertyChange<T= any>(methodName: string, scope?: any) {
2
  return (target: T, key: keyof T): void => {
3
    const originalDescriptor = Object.getOwnPropertyDescriptor(target, key);
4
    let val;
5

          
6
    // Wrap hook methods
7
    Object.defineProperty(target, key, {
8
      set(value) {
9
        const instance = this;
10
        const previousValue = val;
11

          
12
        if (previousValue === value) {
13
          return;
14
        }
15

          
16
        val = value;
17
        if (originalDescriptor) {
18
          originalDescriptor.set.call(instance, value);
19
        }
20

          
21
        if (methodName && val !== previousValue) {
22
          instance[methodName].call(scope || instance, value, previousValue);
23
        }
24
      },
25
      get() {
26
        const instance = this;
27
        if (originalDescriptor) {
28
          return originalDescriptor.get.call(instance);
29
        }
30
        return val;
31
      }
32
    });
33
  };
34
}



And consuming this decorator in your component is straight forward.

JavaScript
 




xxxxxxxxxx
1
22


 
1
import { Component, Input, OnChanges, SimpleChanges, SimpleChange } from '@angular/core';
2
import { OnPropertyChange } from './property-change.decorator';
3
4
@Component({
5
  selector: 'hello-prop-decorator-example',
6
  template: `...`,
7
  styles: [`h1 { font-family: Lato; border-top: 1px solid #CCCCCC;}`]
8
})
9
export class HelloPropDecoratorExampleComponent {
10
11
  public greetings: string = '';
12
13
  
14
  @Input() 
15
  @OnPropertyChange('onNameChange')
16
  name: string;
17
18
  
19
  onNameChange(newName: string) {
20
    this.greetings = newName + '!!!!!';
21
  }
22
}



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


Property (programming)

Opinions expressed by DZone contributors are their own.

Related

  • Comprehensive Guide to Property-Based Testing in Go: Principles and Implementation
  • Implement Hibernate Second-Level Cache With NCache
  • Modify JSON Data in Postgres and Hibernate 6
  • Top 10 C# Keywords and Features

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook