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 Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • Extending Java APIs: Add Missing Features Without the Hassle
  • Effortlessly Streamlining Test-Driven Development and CI Testing for Kafka Developers
  • Auditing Tools for Kubernetes
  • Design Patterns for Microservices: Ambassador, Anti-Corruption Layer, and Backends for Frontends

Trending

  • Extending Java APIs: Add Missing Features Without the Hassle
  • Effortlessly Streamlining Test-Driven Development and CI Testing for Kafka Developers
  • Auditing Tools for Kubernetes
  • Design Patterns for Microservices: Ambassador, Anti-Corruption Layer, and Backends for Frontends

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.

Ashish Patel user avatar by
Ashish Patel
·
Jul. 02, 20 · Tutorial
Like (4)
Save
Tweet
Share
7.20K 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.

Trending

  • Extending Java APIs: Add Missing Features Without the Hassle
  • Effortlessly Streamlining Test-Driven Development and CI Testing for Kafka Developers
  • Auditing Tools for Kubernetes
  • Design Patterns for Microservices: Ambassador, Anti-Corruption Layer, and Backends for Frontends

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: