How To Use OnChanges In Angular?
Last Updated :
30 Aug, 2024
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
project folderDependencies
"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
Similar Reads
How to use jQuery in Angular ?
In this tutorial, we will learn how we can use jQuery with Angular. There are two ways in which we can use jQuery with Angular as discussed below: Table of Content By installing jQuery using the npm commandUsing jQuery CDN to use itBy installing jQuery using the npm commandYou can install the jQuery
2 min read
How to use *ngIf else in AngularJS ?
Introduction: The ngIf directive is used to show or hide parts of an angular application. It can be added to any tags, it is a normal HTML tag, template, or selectors. It is a structural directive meaning that it includes templates based on a condition constrained to boolean. When the expression eva
3 min read
How to use $scope.$apply() in AngularJS ?
In this article, we will be discussing the $apply() function & how to use it in angularjs. In AngularJS, $apply() function is used to evaluate expressions outside of the AngularJS context (browser DOM Events, XHR). Moreover, $apply has $digest under its hood, which is ultimately called whenever
3 min read
How to use Mat-Dialog in Angular ?
Introduction:Angular Material is a UI component library that is developed by the Angular team to build design components for desktop and mobile web applications. In order to install it, we need to have angular installed in our project, once you have it you can enter the below command and can downloa
3 min read
How To Use Reactive Forms in Angular?
In Angular, the forms are an important part of handling user input and validation. Reactive Forms offers a model-driven approach that provides greater control and flexibility by managing form controls, validation, and data binding directly within the component class. Core ComponentsFormGroup: Repres
5 min read
How to select onchange pass option value in angular 6 ?
In this article, we will see how to select onchange pass option value in angular 6, along with knowing the different techniques for retrieving the value of the user-selected item in a dropdown list & will understand their implementation through the illustration. The Dropdown is a commonly used e
5 min read
How to Learn Angular in 2024?
ng new angular-component ng generate component Home ng generate service Home ng serve ng serve --open If you are familiar with these commands, or looking forward to working with these commands then you are in right direction towards the path of learning Angular. If youâre a passionate developer then
9 min read
How to use Angular Material in Angular 17?
Angular Material is a comprehensive UI component library designed specifically for Angular applications. With its large collection of pre-built components and seamless integration with Angular, Angular Material simplifies the process of creating visually appealing and responsive user interfaces. In
2 min read
How to get the value of the form in Angular ?
In this article, we are going to see how to get value from the form in Angular 10. We will use AbstractControl value property to get the form value in an object. Syntax: form.value Return Value: object: It is an object containing form value Approach: Create the Angular app to be usedIn app.component
1 min read
How to Create a new module in Angular ?
Modules are most important when it comes to building strong and scalable Angular applications. They help organize your code, promote modularity, and improve maintainability. It encourages collaboration among developers by grouping related components, directives, pipes, and services. In this article,
3 min read