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

Include a hash in the URL when the current location is entered into the view by scrolling

In my current situation, I am required to implement a @HostListener in order to navigate to an element within my web page: @HostListener('click', ['$event']) onClick(e: any) { e.preventDefault(); const href = e.target.getAttri ...

Can you explain the reference to "ng2" in relation to Angular 2?

In countless blog posts discussing Angular 2, I often come across references to ng2. Can someone clarify what ng2 stands for? Is it the CLI for Angular 2? ...

Issue found in React Js test - TypeError: source.on does not exist as a function

I'm encountering an issue with my post request using multipart/form-data. Everything runs smoothly, except for the tests which are failing. When running the tests, I encounter an error message: TypeError: source.on is not a function. This is the code ...

The angular application is experiencing issues with the injection not functioning correctly

In my MVC application, I have an Angular application that I want to extract and turn into a standalone application. I created a new minimal version of the Angular application using CLI, copied over the package.json file, installed all necessary packages, ...

Having trouble utilizing the Visual Studio Code debugger in an Express.js project that uses TypeScript

My package.json file is shown below: ` { "name": "crm-backend", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev" ...

I am looking to customize the mask input in my angular 7 application so that it allows either a "-" or a digit as the first character, with all subsequent characters being digits. How can I make this modification?

Within my Angular 7 application, I am working on a method that masks user input. Currently, the method restricts users from inputting anything other than digits. However, I need to modify it so that users can input either a "-" or a digit as the first char ...

Error: Loki cannot be used as a constructor

Can anyone assist me in understanding why this code is not functioning correctly? Here's what my index.ts file in Hapi.js looks like: import { Server, Request, ResponseToolkit } from '@hapi/hapi'; import * as Loki from 'lokijs'; ...

Tips for displaying both the time and date using Angular Material Date Picker

I recently integrated the Angular Material date picker control into my Angular project. I want to display both the date and time together. Could someone please advise me on how I can achieve this using the Angular Material date picker control? Appreciate ...

Error in Typescript/React: Unable to access the property 'MaxEmailLength' as it is undefined

I am facing an unusual problem with TypeScript. I have two static classes that are mutually referencing each other and causing issues. Class ValidationHelper (single file) import { ValidationErrors } from '../dictionary/ValidationErrors'; ex ...

Unable to import JSX/TSX component from a separate React application into my primary React application

I find myself facing a challenge with integrating two React applications with different setups. Background: I was assigned the task of developing a design system using ReactJS that would be implemented in their primary application. Despite my limited kn ...

Incorporating Kendo UI and NGX Bootstrap within an Angular application

Currently, I am in the process of developing an Angular application and incorporating the NGX-Bootstrap library. While researching, I came across the Kendo UI library which offers a variety of interesting components. Is it feasible to utilize both librarie ...

What is the most efficient way to find the sum of duplicates in an array based on two different properties and then return the

var data = [ { "amount": 270, "xlabel": "25-31/10", "datestatus": "past", "color": "#E74C3C", "y": 270, "date": "2020-10-31T00:00:00Z", "entityId": 1, "entityName": "Lenovo HK", "bankName": "BNP Paribas Bank", "b ...

Encountering an error message that says "ERROR TypeError: Cannot read property 'createComponent' of undefined" while trying to implement dynamic components in Angular 2

I am currently facing an issue with dynamically adding components in Angular 4. I have looked at other similar questions for a solution but haven't been able to find one yet. The specific error message I am getting is: ERROR TypeError: Cannot read ...

Get every possible combination of a specified length without any repeated elements

Here is the input I am working with: interface Option{ name:string travelMode:string } const options:Option[] = [ { name:"john", travelMode:"bus" }, { name:"john", travelMode:"car" }, { name:"kevin", travelMode:"bus" ...

Handling HTTP Errors in Angular Components with NGRX

I have successfully integrated the store into my angular project. I am able to handle and process the successSelector, but I am facing difficulty in capturing any data with the errorSelector when an HTTP error occurs from the backend. The error is being c ...

Troubleshooting Angular 2 Final Release Visual Studio - encountering issues with finding module name and incorrect module.id path leading to 404 errors

After upgrading to the Angular 2 Final Release (I am using Visual Studio 2015 and TypeScript 1.8), I noticed that my line moduleId: module.id in my components now has a red squiggly underline and displays an error saying cannot find name 'module' ...

Encountered an error while trying to access the 'touched' property of undefined within Angular6 reactive forms

When attempting to validate my page, I encountered an error stating 'Cannot read property 'touched' of undefined'. Can someone please assist me with this code? Also, feel free to correct any mistakes you may find. Here is the HTML code ...

Issues with Angular Structural Directives arising from NPM installation concerns are causing problems

I have developed an npm package called sezam-shareds To integrate the package into a new project, you need to follow these steps: Add the following component from the package: <sezam-overflow [show]="true"></sezam-overflow> to a compo ...

Printing content from an Angular dashboard can be achieved by following a few

Currently, I am working on developing a legal document automation program for my company. However, I have encountered an issue during the final stages of completing this web application. For the layout and setup, I am using the default angular Dashboard l ...

How do I create a standalone .ts file with Angular 9?

Just diving into Angular development and eager to create a standalone .ts file without having to generate an entire component. Can anyone guide me on how to achieve this using ng generate? Scenario: During the application build process, I need to write th ...