Open In App

How To Use OnChanges In Angular?

Last Updated : 30 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Angular is a powerful framework for building dynamic web applications, and one of its core features is the ability to manage and react to changes in component data. One of the key lifecycle hooks in Angular for responding to changes in input properties is the OnChanges lifecycle hook.

This hook is handy when a component's inputs change dynamically, allowing you to perform custom logic whenever those inputs are updated. In this article, we will see how to use OnChanges in Angular.

Prerequisites

The OnChanges lifecycle hook in Angular is triggered when the input properties of a component or directive change. It allows you to react to changes in the input values and perform necessary actions based on those changes. The onChanges interface contains a method ngOnChanges() that retrieves a SimpleChanges object which holds the current and previous values of the inputs.

Approach To Use OnChanges in Angular

In this approach, the component class implement the OnChanges interface which mandates the implementation of the ngOnChanges method. This method is called whenever any of the @Input properties of the component change.

  • Implement the OnChanges interface in your component
  • Define a ngOnChanges method that receives a SimpleChanges object
  • Access the changed input properties using
changes['inputName'].previousValue
changes['inputName'].currentValue
  • Use this method to perform any actions you need to take when an input property changes.

Steps To Use OnChanges in Angular?

Here we create a sample angular application by using commands once the project is created successfully then we started implement the logic for OnChanges in angular. For this please follow below step by step process.

Step 1: Create a New Angular Project

ng new onchanges
cd onchanges

Folder Structure

Screenshot-2024-08-21-124724
project folder

Dependencies

 "dependencies": {
"@angular/animations": "^17.3.0",
"@angular/common": "^17.3.12",
"@angular/compiler": "^17.3.0",
"@angular/core": "^17.3.0",
"@angular/forms": "^17.3.0",
"@angular/platform-browser": "^17.3.0",
"@angular/platform-browser-dynamic": "^17.3.0",
"@angular/router": "^17.3.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
}

Step 2 : Implement Logic For OnChanges

Now implement the required logic for OnChanges in Angular. For this we changes source code of below mentioned files. And we provide source code for your reference. Here we use Bootstrap framework in the form CDN links and integrated in the index.html file of the project.

HTML
<!--app.component.html-->

<div class="container p-5 bg-success mt-5">
    <p class="mt-5 text text-light" style="font-weight: bolder;">Data: {{ data }}</p>
    <button (click)="changeData()" class="btn btn-light text-success">Change Data</button>
</div>
HTML
<!--index.html-->

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>Onchanges</title>
    <base href="/">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="favicon.ico">
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</head>

<body>
    <app-root></app-root>
</body>

</html>
JavaScript
//app.component.ts

import { Component, OnChanges, SimpleChanges } from '@angular/core';
import { RouterOutlet } from '@angular/router';

@Component({
    selector: 'app-root',
    standalone: true,
    imports: [RouterOutlet],
    templateUrl: './app.component.html',
    styleUrl: './app.component.css'
})
export class AppComponent implements OnChanges {
    title = 'onchanges';
    data: string = 'Initial Data';

    ngOnChanges(changes: SimpleChanges): void {
        if (changes['data']) {
            console.log('Previous:', changes['data'].previousValue);
            console.log('Current:', changes['data'].currentValue);
        }
    }

    changeData() {
        this.data = 'Updated Data';
    }
}


To start the application run the following command.

ng serve --open


Output


Next Article

Similar Reads