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 $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 the Async Pipe in Angular?
The AsyncPipe in Angular is a powerful and convenient tool used to handle asynchronous data streams such as observables and promises directly in the component template. It automatically subscribes to observables, renders their values, and updates the view when new data is emitted. This removes the n
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 Use ViewChild in Angular?
In Angular, ViewChild is a powerful decorator that allows you to access and manipulate child components, directives, or DOM elements from a parent component. This feature is essential for scenarios where the parent needs to interact with its child components directly, such as invoking methods, acces
3 min read
How to Learn Angular in 2024?
ng new angular-componentng generate component Homeng generate service Homeng serveng serve --openIf 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 sure
9 min read
How To Use ngx-translate with Angular?
Weâll walk through how to use ngx-translate Angular to add multilingual support to your application. Youâll learn how to set up @ngx-translate/core and @ngx-translate/http-loader to pull in translation files stored in the assets directory. Weâll cover how to create translation keys, using the transl
3 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.componen
1 min read