Identifying Shifts in Objects Using Angular 5

Is there a way to detect changes in an object connected to a large form? My goal is to display save/cancel buttons at the bottom of the page whenever a user makes changes to the input.

One approach I considered was creating a copy of the object and using *ngIf="object !== object_copy". If the user hits cancel, I would simply revert back to the copied object. However, I'm not sure if this method is efficient since it involves doubling the variables for a simple task. I'm relatively new to Angular and struggling to implement this method as making a copy seems to cause the object to lose its type.

I'm seeking guidance or suggestions on alternative methods to achieve this. Can anyone assist me with this issue?

Answer №1

If you happen to be utilizing a Form, Angular's form control feature can be quite useful. It provides notifications whenever a form or any of its values are modified in any way. Here is a simple example of how you could utilize this:

form.dirty

You can also target specific fields for more focused functionality. The possibilities with reactive and template forms in Angular are endless.

https://angular.io/guide/forms

Answer №2

To properly handle the change event, you must subscribe to an event as shown below:

constructor(private formBuilder: FormBuilder) {
    this.myForm = formBuilder.group({
      name: 'Alice Smith',
      age: 30
    })

    this.myForm.valueChanges.subscribe(data => {
      console.log('Form data has changed', data);
    })
  }

This implementation should function correctly.

Answer №3

A feature in ReactiveForm is the dirty property which allows you to easily check the form's dirty status with 'myForm.dirty'.

If you want to set the initial value of the form to an object property, you can achieve this by using the getRawValue() method.

this.initialFormValue = this.myForm.getRawValue();

To monitor form changes, simply subscribe to the form using:

myForm.valueChanges.subscribe((value) => {

  this.updatedFormValue = this.myForm.getRawValue();

},
(err) => {
//
}
);

With both the initial and current form values, you can now compare them and proceed accordingly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unexpected Type Error: Unable to Assign 'Render' Property to Undefined

At the moment, I am encountering these specific issues: An Uncaught TypeError: Cannot set property 'render' of undefined The element #main cannot be found This is the code that I currently have. Despite looking for solutions from various sourc ...

Confirming the presence of an image using jQuery without enforcing it as mandatory

Situation: In my setup, I maintain a database that holds details about various items. Currently, I utilize a dynamic form to retrieve and exhibit the existing information on any item stored in the database. Any modifications made on the form are promptly ...

Updating Select Options with Multiple Values using Javascript

My goal is to update the selected value of multiple select elements simultaneously using JavaScript. However, I am facing an issue where my script only updates one select element instead of all of them on the page. Unfortunately, I cannot modify the id att ...

NavLinkButton - add style when active or selected

I'm working with a list of NavLinks: const users = Array.from(Array(5).keys()).map((key) => ({ id: key, name: `User ${key}`, })); <List> {users.map((user) => { return ( <ListItem disablePadding key={user.id}> ...

Combining strings using the PHP preg_replace function

I'm looking for assistance with using Ajax to send JS variables to my PHP script in order to modify the background color. Can you provide guidance on how to achieve this? I am struggling with how to concatenate strings and utilize the $mavariable vari ...

The element in Selenium's net.serenity.bdd.core.exceptions.SerenityManagedException has encountered a timeout issue

I'm having difficulty choosing a radio button on this particular form: <form _ngcontent-c4="" novalidate="" class="ng-untouched ng-pristine ng-invalid"> <div _ngcontent-c4="" class="text-center"> <div _ngcontent-c4="" class=" ...

Enhancing Luxon DateTime with extension type support

Referencing the issue at https://github.com/moment/luxon/issues/260, I am looking to extend the DateTime object as shown below: import { DateTime } from 'luxon'; function fromUnix(tsp?: number): DateTime { return DateTime.fromMillis(tsp * 1000 ...

Is there a way to incorporate cell highlighting on IE?

I've implemented a method to highlight selected cells based on the suggestion from jointjs. It surrounds the cell with a 2-pixel red border, which works well in Chrome. However, I need the outline to work in IE as well. Unfortunately, when I reviewed ...

Mastering regular expressions in TypeScript

My goal is to perform linting on staged files that are either .ts or .tsx and located within the src folder. I am aware that for selecting all js files one can use "*.js": [--list of commands--] inside the lint staged property. I'm curious to learn m ...

Webpack is throwing an error stating that it cannot find a module with the relative path specified

Here is the structure of my app (excluding the node_modules directory): ├── actions.js ├── bundle.js ├── components │   ├── App.js │   ├── Footer.js │   ├── Link.js │   ├── Todo.js │   └─ ...

Percy snap shot test cannot be executed in Testcafe due to the error message: npm ERR! The script 'test:percy' is

For my initial test with percy snapshot, I used the command below: npm run test:percy Unfortunately, an error message appeared when running the command: xxx.xxx@LPG002572 TC-Visual % npm run test:percy npm ERR! missing script: test:percy npm ERR! A com ...

Attempting to sort data with AngularJS

I'm currently working on implementing 'order by' functionality in my Angular app. Here's what I've attempted: <div *ngFor = "let movie of webService.movie_list | async | orderBy:'Year'"> However, when testing it ...

Accessing Route Parameters from Any Component

If my URL follows this structure: /blog/[post_id]/something What's the best practice for passing $post_id to any component within the tree? I'm familiar with retrieving route parameters using getInitialProps, but I struggle with passing values ...

I am looking to transfer the value of one textbox to another textbox within a dynamic creation of textboxes using JavaScript

var room = 1; function add_fields() { room=$('#row_count').val()-1; room++; var objTo = document.getElementById('education_fields'); var divtest = document.createElement("div"); divtest.setAttribute("class", "form- ...

I'm curious about why I'm receiving the error "Unable to bind to 'ngFor' since it is not recognized as a property of 'li'. Can someone please explain why this is happening?

The issue is related to the *ngFor directive for nonvegfoodlist app.component.ts import { Component } from '@angular/core'; export class Menu { id : number; name :string; } const veg : Menu[] = [ { id:1 , name:'Rice'}, { id: ...

The type 'any' cannot be assigned to the type 'never' as a parameter

const [files, setFiles] = useState([]) const handleChange = (event: any) => { setFiles.push(event.target.files[0].name) return (<div> {files.map((file: any) => ( <p>Hello!</p> ))} </ ...

Receiving messages in AngularJS with the help of Strophe.js

My XMPP client in AngularJS, inspired by this stackoverflow link. <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5d282e382f1d282e382f7331323e3c31">[email protected]</a> can send messages successfully, but <a hr ...

Issue with Browsersync causing task to malfunction in Gulp 4

Gulp Local v4.0.2, CLI v2.3.0 Browsersync v2.26.13 gulpfile.js: 'use strict' const gulp = require('gulp') const concat = require('gulp-concat') const babel = require('gulp-babel') const uglify ...

The Kendo Grid is not displaying any data when trying to bind the data source using an ajax callback to the controller

My query is quite similar in nature to this: Binding Kendo Data Source with Async $.ajax calling from C# MVC Controller Action Below is the javascript code used for generating the Kendo grid: $(document).ready(function () { $("#grid").kendo ...

`Warning: The alert function is not working properly in the console error

I am currently working on integrating otp functionality into my Ionic 3 project. I am facing an issue where I am able to receive the otp, but it is not redirecting to the otp receive page due to a specific error. Below is the console error that I am encou ...