Angular
Web Development
JavaScript
Programming
Input Value Changes

How to detect when an @Input() value changes in Angular?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

In Angular, component interactions often rely on the use of @Input() properties to pass data from a parent component to a child component. Detecting changes in these input properties is essential for performing operations like updating the child component's display or processing the data received. Angular provides several methods to handle changes in input properties effectively.

Using ngOnChanges Lifecycle Hook

One of the primary ways to detect changes in input properties in Angular is by using the ngOnChanges lifecycle hook. This hook is called whenever one or more data-bound input properties change. The method receives a SimpleChanges object that contains the current and previous property values.

Here is a basic example:

typescript
1import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
2
3@Component({
4  selector: 'app-sample',
5  template: `<p>{{ name }}</p>`
6})
7export class SampleComponent implements OnChanges {
8  @Input() name: string;
9
10  ngOnChanges(changes: SimpleChanges) {
11    if (changes['name']) {
12      console.log('Name changed from', changes['name'].previousValue, 'to', changes['name'].currentValue);
13    }
14  }
15}

In this example, the SampleComponent listens for changes to the name input property. Inside the ngOnChanges method, a check is performed to see if the name input property has changed, and if so, it logs the change.

Using a Setter for @Input()

Another way to react to changes in @Input() properties is to use a setter. This approach offers more control over a single or specific property and is useful when you need to execute some logic as soon as the property changes.

Here’s how you can implement it:

typescript
1import { Component, Input } from '@angular/core';
2
3@Component({
4  selector: 'app-sample',
5  template: `<p>{{ name }}</p>`
6})
7export class SampleComponent {
8  private _name: string;
9
10  @Input()
11  set name(name: string) {
12    this._name = name;
13    console.log('Name is set to', name);
14  }
15
16  get name(): string {
17    return this._name;
18  }
19}

In this example, any change to the name input property immediately triggers the setter, allowing you to run custom logic (here, simply logging the new name).

Using ngDoCheck Lifecycle Hook

For more control or more complex scenarios, you can use the ngDoCheck lifecycle hook. This method is called with every change detection cycle, so it provides a place to implement custom change detection logic.

typescript
1import { Component, Input, DoCheck, KeyValueDiffers } from '@angular/core';
2
3@Component({
4  selector: 'app-sample',
5  template: `<p>{{ name }}</p>`
6})
7export class SampleComponent implements DoCheck {
8  @Input() name: string;
9  private differ: any;
10
11  constructor(private differs: KeyValueDiffers) {
12    this.differ = this.differs.find({}).create();
13  }
14
15  ngDoCheck() {
16    const change = this.differ.diff(this);
17    if (change) {
18      console.log('Changes detected');
19    }
20  }
21}

While powerful, ngDoCheck can lead to performance issues if not used carefully due to its frequent invocation.

Summary Table

MethodUsage ScenarioEfficiency
ngOnChangesDetecting changes to one or more data-bound input propertiesHigh
Setter for @InputSpecific logic on property change, control over a single propertyMedium to High
ngDoCheckComplex scenarios, custom tracking needsLow (Cautious use advised)

Conclusion

Detecting changes to @Input() properties in Angular can be accomplished through various methods depending on the complexity and specific requirements of your application. Using lifecycle hooks like ngOnChanges and ngDoCheck, or employing property setters, provide robust options to handle incoming data efficiently and reactively in your Angular components.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.