Angular - Evaluating the differences between the object model and the original model value within the view

To enable a button only when the values of the 'invoice' model differ from those of the initial model, 'initModel', I am trying to detect changes in the properties of the 'invoice' model.

This comparison needs to happen in the view like this:

<button mat-button (click)="saveChanges()" [disabled]="invoice !== initModel">Save Changes</button>

The 'invoice' model is initialized by assigning it the value of another variable from a service in the constructor.

I attempted to set an 'initModel' component variable, but since it binds with the 'invoice' model, any changes in 'invoice' lead to changes in 'initModel'. Therefore, I couldn't define 'initModel' as a constant accessible in the view.

Component:

export class EditInvoiceComponent implements OnInit {

  invoice: Invoice;
  initModel;

  constructor(private invoicesService: InvoicesService) {
    this.invoice = this.invoicesService.selectedInvoice;
    this.initModel = this.invoice;
  }

Answer №1

When you first initialize the initModel, you are not actually creating a new object; instead, you are simply passing a reference to the existing invoice object.

To create a copy (not a deep clone) of the original object, you can utilize the Spread Operator in this way:

this.initModel = {...this.invoice};

For deep cloning purposes, external libraries like lodash can be used. For more information on efficient ways to perform deep cloning in JavaScript, refer to this insightful answer.

Answer №2

Give the following code a try:

$scope.hasChangedInvoiceValue = false;
$scope.$watch('invoice', function (newValue, oldValue, scope) {
    // Add your logic here to validate value changes with initModel
    $scope.hasChangedInvoiceValue = true | false; // Set based on your logic
}, true); // Use true if you need to watch nested properties for changes

<button mat-button (click)="saveChanges()" [disabled]="hasChangedInvoiceValue">Save Changes</button>

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

Valid method of confirming a user's login status

Using AJAX requests, I have implemented a user area on my website. The "Log off" button is supposed to be displayed only when the user is logged in. Here is the AJAX request for logging in a user: function requestSI() { var xhr = getXMLHttpRequest(); xhr ...

Do we really need to use the eval function in this situation?

Just wondering, is it reasonable to exclude the eval() function from this code? Specifically how <script> ... ... function addGeoJson (geoJsonPath, iconPath = "leaflet-2/images/marker-icon.png", iconSize = [30,50], popUpContent, ...

Customizing the Switch component individually for each item fetched from an API in React Native

I'm struggling with setting the switch button individually for each item in my API. Despite trying multiple solutions, none of them seem to work for me. const results = [ { Id: "IySO9wUrt8", Name: & ...

Attempting to install angular-in-memory-web-api using npm, but encountering various errors in the process

When trying to install angular-in-memory-web-api using npm, an error with code ERESOLVE occurred. The dependency tree could not be resolved, causing a conflict. While resolving dependencies for the project, it was found that @angular/common version ~13. ...

Angular2 - Implementing Form Validation for Dynamically Generated Input Fields Based on Conditions

My goal is to create a basic form that allows users to select between two options: Local and Foreigner. If the user does not make a selection, the form should be marked as invalid. Choosing Local will make the form valid, while selecting Foreigner will rev ...

The issue of Access-Control-Allow-Origin restriction arises specifically when using the gmap elevation API

My attempts to retrieve the elevation of a site using latitude and longitude have been unsuccessful due to an error I encountered while making an ajax call. Regardless of whether I use HTTP or HTTPS, I receive the following error message: "No 'Access ...

Ignore missing values when performing an upsert operation

I'm currently utilizing pg-promise to manage my Postgres queries, but I've hit a roadblock with the following query conundrum: My goal is to develop a single method that can batch upsert multiple rows simultaneously. Here's the code snippet ...

Is your Angular 2 routing failing to work properly after a page refresh or reload when using gulp?

I've recently started learning Angular 2, and I encountered an issue with routing. During the development phase, I ran my application using npm start. However, after migrating to gulp.js, when I run the application by typing gulp, everything works fin ...

Why is the ionChange/ngModelChange function being triggered from an ion-checkbox even though I did not specifically call it?

I have an issue with my code involving the ion-datetime and ion-check-box. I want it so that when a date is selected, the checkbox should automatically be set to false. Similarly, if the checkbox is clicked, the ion-datetime value should be cleared. Link ...

What is the best way to extract information from a button and populate a form in AngularCLI?

I am currently attempting to enhance my Angular App by using a button to transfer information to a form upon clicking, rather than the traditional radio buttons or select dropdowns. My objective is to incorporate HTML content into the button (such as Mat-I ...

Retrieve the identifier of the higher-order block when it is clicked

When I have a parent block with a nested child block inside of it, I expect to retrieve the id of the parent when clicked. However, the event target seems to be the child element instead. Is there a way for JavaScript to recognize the parent as the event ...

In what way can I indicate parsing "per dataset" using Chart.js?

I'm currently exploring the usage of the yAxisKey option in ChartJS while defining a dataset. However, I'm encountering difficulties in replicating this specific example from the documentation. Despite my efforts to search for issues related to y ...

Tips on transforming truncated surfaces into complete entities

When working in Three.js, I encountered a situation with a 3D object where local clipping planes were used to render only a specific part of the object. However, due to the nature of 3D objects being "hollow" (only rendering the outer surface), when somet ...

The Autocomplete component from MUI is alerting me to provide a unique key for every child element being passed

I am currently using the Autocomplete component from MUI and encountering an issue with a warning that says: Warning: Each child in a list should have a unique "key" prop. Although I've added keys to both renderOption and renderTags, the wa ...

The element within the iterator is lacking a "key" prop, as indicated by the linter error message in a React component

Encountering an error stating Missing "key" prop for element in iteratoreslintreact/jsx-key {[...Array(10)].map((_) => ( <Skeleton variant="rectangular" sx={{ my: 4, mx: 1 }} /> ))} An attempt to resolve this issue was made ...

Using Typescript generics within a callback function

I am currently working on developing a versatile service that can fetch data from a remote source and create objects based on that data. @Injectable() export class tService<T> { private _data: BehaviorSubject<T[]> = new BehaviorSubject([]) ...

Ways to remove cdk-overlay-container

I am currently working on an Angular project (version 9.1.4) that utilizes ng-bootstrap (version 6.1.0) to display modals. I have observed that whenever a modal is opened, it adds <div class='cdk-overlay-container' /> to the HTML structure. ...

Utilizing Express, Request, and Node.js to manage GET requests in typescript

I'm struggling with using Express and Request in my project. Despite my efforts, the response body always returns as "undefined" when I try to get JSON data from the server. In my server.js file, this is the code snippet I have been working on: impo ...

Tips on preventing image previews from consuming too much text data while updating a database in Angular 12 using Material UI for image uploads within a FormGroup object

Currently working with Angular 12 and Angular Material for image uploads with preview. I have a formgroup object below, but I'm running into issues with the 197kb image preview text being inserted into the database. Despite trying setValue/patchValue/ ...

In ES6, instantiate a fresh new instance of this

Can a new instance of self/this be generated using ES6 inside a static method? For instance; class myClass { static model() { return new this; } } Is there a standard approach for this situation? Thank you very much. ...