The assignment to 'total' is prohibited as it is either a constant or a property that is read-only within the get total() function

After running the command ng build --prod in my project, I encountered the following error message: "Cannot assign to 'total' because it is a constant or read-only property for function get total(){}"

The function causing the issue is:

  get total() {
         return this.products
          .map(p => p.Unit_price * p.Quantity)
          .reduce((a, b) => a + b, 0);
      }

This is how it is implemented in the HTML:

<form [formGroup]="addsale" (ngSubmit)="onaddsale()" >
  <div class="row">
    <div class="input-field col s2" style="float: right;">
      <label for="total">Total {{total}} ALL</label>
      <input formControlName="total" id="total" type="text" class="validate" [value]="total" [(ngModel)]="total">
    </div>
    <div class="input-field col s2" style="float: right;">
      <label for="amount_paid">Amount Paid:</label>
      <input formControlName="amount_paid" id="amount_paid" [value]="total" type="text" class="validate" [(ngModel)]="total">
    </div>
    <div class="input-field col s2" style="float: right;">
      <label for="total">Subtotal</label>
      <input formControlName="Subtotal" id="Subtotal" type="text" class="validate" [value]="total" [(ngModel)]="total">
    </div>
  </div>
</form>

The TypeScript form definition is as follows:

   this.addsale = this.fb.group({
      'amount_paid': new FormControl('', Validators.required),
       'Subtotal': new FormControl('', Validators.required),
      'total': new FormControl('', Validators.required)
    });

If you have any ideas on how to resolve this issue, please let me know. Thank you!

Answer №1

When you build with the --prod flag, it actually compiles with aot (ahead of time compilation), which is more stringent than simply using ng serve.

The issue may be due to all your fields having [(ngModel)] set to total, causing conflicts with the total getter when using two-way bindings (get/set).

Considering that the total is dynamically calculated, having a two-way binding for total doesn't seem appropriate; it should be read-only. Furthermore, subtotal and amount paid should not use total as their ngModel values.

Answer №2

I encountered a similar issue, but mine was related to the form's valid status.

<-- HTML -->
<button 
    type="submit"
    [(disabled)]="!loginForm.valid">
    Enter
</button>

What solved the problem for me was creating a new public variable to store the validity check.

<-- JS -->
public validForm: boolean;

 ngOnInit() {
     this.validForm = this.loginForm.valid;
 }
<-- HTML -->
<button 
    type="submit" 
    [(disabled)]="!validForm">
    Entrar
</button>

<--- EDIT --->

Another solution is to use one-way data binding only.

<button 
    type="submit" 
    [disabled]="!loginForm.valid">
    Entrar
</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

Why is it that my service in the Angular project doesn't fetch data after I make changes and reload the page?

When a user selects a customer, I have a method that fetches the customer's ID from the database and saves it to local storage. However, if I make changes to my code and refresh the page after selection, it doesn't fetch the customer ID. How can ...

What is the best way to transform this date string into a valid Firestore timestamp?

Currently, I am facing an issue in my Angular application that is integrated with Firebase Firestore database. The problem lies in updating a date field from a Firestore timestamp field. To provide some context, I have set up an update form which triggers ...

Is there a way to access every item that includes a particular attribute and attribute term within the woocommerce-rest-api?

Struggling to retrieve products that have the "x-attribute" and "x-attribute-term" using Node.js with the WooCommerce REST API library from here. I've explored solutions on stackoverflow and other sites but none seem to work. Atte ...

Attention! Circular dependency has been detected during compilation with warnings

Every time I attempt to build my project, an error is thrown- WARNING in Circular dependency detected: src\app\own-filter\own.filter.module.ts -> src\app\own-filter\own.filter.component.ts -> src\app\own-f ...

The correlation between the node.js version and the @types/node version

I recently started exploring node.js and decided to experiment with using TypeScript alongside it. After running npm install @types/node, I found that the latest version available was 7.0.4: $ npm install @types/node <a href="/cdn-cgi/l/email-protectio ...

Guide on Implementing Class on Dropdown in AngularFollow these steps to effectively utilize the

Currently, I am facing an issue with my Angular project. I am trying to implement a Directive that activates a dropdown menu. However, the 'open' class is deprecated in Bootstrap 3, and I am using Bootstrap 5. How can I transition to the 'sh ...

Is it advisable to send an http request within the ngOnInit of an Angular Universal component?

During my Angular app development, I did not encounter any errors while running it via ng serve. However, when I switched to SSR (Server-Side Rendering), I started receiving an error in my server log whenever a component that makes an http request as part ...

Closing iframe in Angular 4 after redirection

I am currently working on an Angular 4 application that involves integrating a third-party payment system called Tranzila. Tranzila offers a convenient integration method using an iframe, allowing users to make payments on their domain without me having to ...

Avoid using `object` as a data type, as it can be challenging to work with

const useSetState = <T extends dataStructure>( initialState: T = {} as T ): [T, (patch: Partial<T> | ((prevState: T) => Partial<T>)) => void] => { const [state, setState] = useState<T>(initialState); const setMergeSta ...

The deployment of my Node application on Heroku is causing an error message: node-waf is not

I've been trying to deploy my Node.js application on Heroku by linking it to my Github repository and deploying the master branch. Despite experimenting with various methods, I keep encountering the same error every time. You can view the detailed b ...

Unlock the power of Angular ViewChildren to access and manipulate SVG elements efficiently

I have an SVG file loaded as an object: <object data="assets/img/states.svg" type="image/svg+xml" id="map"></object> This SVG includes a large PNG map along with several rect and text elements. <rect y="224.72084" x="644.87109" ...

Why is the AngularJS 2 child @Component not being replaced in this scenario?

UPDATE: It seems that the issue lies in how I am structuring and serving the project rather than a coding problem. If I find a solution, I'll be sure to update this post. Thank you for your assistance. I'm currently developing an AngularJS 2 ap ...

What is the best way to remove a specific row from an Angular Material table that does not have any filters

Here is my samplepage.component.ts code: import { Component } from '@angular/core'; @Component({ selector: 'app-batchticketvalidation', templateUrl: './batchticketvalidation.component.html', styleUrls: ['./batchtic ...

I am experiencing difficulties with integrating the Stripe checkout API into my MEAN stack development

view error image here I encountered this issue in the developer tools. check terminal error image here This is the error shown in the backend terminal. explore Stripe documentation for guidance Here are the helpful Stripe docs that guided me through. ...

Creating an array of objects in Angular 2

I'm facing an issue with the following expression: public mySentences:Array<string> = [ {id: 1, text: 'Sentence 1'}, {id: 2, text: 'Sentence 2'}, {id: 3, text: 'Sentence 3'}, {id: 4, text: 'Sen ...

Improving Accessibility in Angular 10 by Confining Focus within Modals

I'm currently working on updating my existing modal popup to ensure ADA compliance. I am using a user-defined handleTabKeyFocus() function to manage the keyboard Tab focus within the modal container. However, the querySelector selector always returns ...

Efficiently integrating Firebase Functions with external sub path imports beyond the project's

I encountered an issue in my firebase functions project with typescript. The problem arises when I use types from outside the project with sub path imports, causing the build files to become distorted. Instead of having main:lib/index.js, I have main:lib/ ...

The attribute 'checked' is not a valid property for the 'TElement' type

Learning about typescript is new to me. I have a functional prototype in fiddle, where there are no errors if I use this code. http://jsfiddle.net/61ufvtpj/2/ But in typescript, when I utilize this line - if(this.checked){ it presents an error [ts] Pro ...

Encountering an HTTP parsing failure while sending XML through Angular 5's HttpClient

Struggling to access a local webservice through XML: Take a look at the code below: const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'text/xml', 'Accept': 'text/xml', 'Response- ...

Is there a way to use Lodash to quickly return the same value if a condition is met using the ternary operator

Is there a condensed way to do this using Lodash? (or perhaps Vanilla JS/TypeScript) var val = _.get(obj, 'value', ''); Please note that var val = obj.value || ''; is not suitable as it considers 0 and false as valid but fal ...