You are unable to assign to 'total' as it is a constant or a property that cannot be modified

Upon running ng build --prod in my project, I encountered the following error:

src\app\components\xxxx\xxxx.component.html(116,100): : Cannot assign to 'total' because it is a constant or a read-only property.

The problematic line of code is as follows:

<input formControlName="total" id="total" type="text" class="validate" [(ngModel)]="total">

I utilized [(ngModel)]="total" in order to save the value even if left unmodified. Using [value]="total" eliminates this error but does not retain the value unless modified.

The total value is retrieved using the following function in TypeScript. This value is Read-Only:

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

This total represents the sum of all product totals.

How can this code be adjusted to function properly?

Edit:

HTML Code:

<form [formGroup]="addsale" (ngSubmit)="onaddsale()">
  <table align="center" class="table table-bordered table-hover">
    <thead>
      <tr style="color:black;">
        <th>p_Product_type_id</th>
        <th>p_product_id</th>
        <th>p_Unit_price</th>
        <th>p_Quantity</th>
        </tr>
    </thead>
    <tbody>
      <tr class="group" *ngFor="let item of products">
        <td>{{item.p_Product_type_id}}</td>
        <td>{{item.p_product_id}}</td>
        <td>{{item.p_Unit_price}}</td>
        <td>{{item.p_Quantity}}</td>
      </tr>
    </tbody>
  </table>
  <br>
  <br>
  <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="total">Subtotal</label>
      <input formControlName="Subtotal" id="Subtotal" type="text" class="validate" [value]="total" [(ngModel)]="total">
    </div>
  </div>
  <hr>
  <br>
  <div id="add_homebox_button_container" class="row" style="float: right;">
    <button id="add_client_button" type="submit" class="btn waves-effect waves-light">
      Register
    </button>
</form>

TypeScript Code:

export class component implements OnInit {
  constructor(.............
  ) {

    this.addsale = this.fb.group({
      'Subtotal': new FormControl('', Validators.required),
      'products': this.fb.array([]),
      'total': new FormControl('', Validators.required),

    });

  }

  ngOnInit() {
    this.allproducts();

  allproducts() {
    this.products = this.ps.getProduct();
  }


  onaddsale() {
    this.areWeWaiting = true;
    let sale = this.addsale.value
    sale.products = this.products
    let newSale = new Sale(sale);

    this.ws.saleitemcreate(newSale).subscribe(
      result => {
        if (result === true) {
          Materialize.toast('Successfully', 4000);
        } else {
          this.areWeWaiting = false;
        }
      },
      error => {
        this.areWeWaiting = false;
      }
    );
  }

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

Answer №1

Make use of the code snippet [value]="total" and ensure to add the total to stored values during saving. There is no need to rely on the form for gathering values to save; this can be managed within your component.

In my opinion, resorting to ngModel solely for passing a value for saving seems like a workaround approach.

I would suggest amending the onaddsale method to incorporate the total in the sale. Subsequently, you could eliminate the inclusion of total from the fb.group() and remove the reference to formControlName="total" in the template as it's not essential.

  onaddsale() {
    this.areWeWaiting = true;
    let sale = this.addsale.value;
    sale.products = this.products;
    // include total here
    sale.total = this.total;
    let newSale = new Sale(sale);
    ...
  }

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

Issue with sx prop type error found in the TabPanel component of MUI v5

My first time using MUI with TypeScript has hit a roadblock with the new sx prop. Check out the error displayed by TypeScript in the screenshot linked below: https://i.sstatic.net/JYDTX.png Interestingly, the error only pops up on the TabPanel Component, ...

Utilizing the await keyword within a forkJoin operation in TypeScript

I am facing an issue where I need to fetch a new result based on the old result. When a specific parameter in my primary call is X, it should trigger another function. However, the problem I'm encountering is that the scope of the program continues ru ...

Within Angular, the Subscribe function is invoked after all other methods in the component have been executed. Consequently, this sequence of events often prevents me from effectively utilizing the response data

Struggling with implementing await and async in TypeScript, especially as a beginner. Below is how I attempted to use them: async refreshList(){ await this.service.refreshList().subscribe(res => { console.log(res); this.service.todoListModel=res; ...

Is there a way to reverse the color scheme on ngx-charts-heat-map?

I have been successfully using the ngx-charts-heat-map to generate a heat map. Everything seems to be working fine, but I am facing a small issue that I can't seem to figure out. Currently, the color of each cell on the map corresponds to its value ...

Utilizing Typescript to define key-value pairs within a structured form

I've been creating a form structure that's functioning smoothly, but I've encountered an interesting issue with field validation in the validation part. While my Visual Code is pointing out that 'required2' in the phone constant n ...

Using TypeScript to import a Vue 2 component into a Vue 3 application

Recently, I embarked on a new project with Vue CLI and Vite, utilizing Vue version 3.3.4 alongside TypeScript. In the process, I attempted to incorporate the vue-concise-slider into one of my components. You can find it here: https://github.com/warpcgd/vu ...

Acquiring information from a Service and saving it in a Child component - Angular version 11

Utilizing my service, I fetch API data for the child component. Initially, it retrieves the Id and other user data, displaying it in the console. ngOnInit(): void { this.commonService.userSetChange.subscribe( apiData => { this.getUserS ...

Is there a way to retrieve the name of a document stored within a collection using Firebase Firestore and Firebase Storage

When fetching data from the 'users' collection in Firebase Firestore and mapping the response, I have a function that converts the array of domains and filters out any domains that do not meet certain criteria. Here's an example: Sample dom ...

What is the best way to create a personalized filter function for dates in JavaScript?

I am working with a DataTable that includes a column called Timestamp: <p-dataTable sortMode="multiple" scrollable="scrollable" scrollHeight="150" [value]="currentChartData" #dt> <p-column field="timestamp" header="Timestamp" [sortable]=" ...

Finding the location of an "Apply" button on an Angular HTML page

There is an issue with the positioning of the apply button in the filter bar. Sometimes it displays in the next row instead of alongside the other filters. How can I determine the exact position of this apply button within the HTML page? <div class=&quo ...

How can a component properly accept a class as an input and integrate it with its own classes?

Consider a scenario where a component dynamically assigns values to the class attribute of its host element based on specific runtime conditions. For instance, let's analyze this TextBox component that sets class values depending on the readonly and ...

Send the index of the row to the event handler in the table of data

I am currently utilizing a data table component from PrimeNG and have the following template code: <p-column [style]="{'width':'40px'}"> <template let-col let-rowData="rowData" let-rowIndex="rowIndex" pTemplate type="body" ...

What steps are involved in setting up a Typescript-based custom Jest environment?

Currently, I am attempting to develop an extension based on jest-node-environment as a CustomTestEnvironment. However, I encountered an error when trying to execute jest: ● Test suite failed to run ~/git/my-application/tests/environment/custom-test ...

Creating an enum from an associative array for restructuring conditions

Hey everyone, I have a situation where my current condition is working fine, but now I need to convert it into an enum. Unfortunately, the enum doesn't seem to work with my existing condition as mentioned by the team lead. Currently, my condition loo ...

What are the consequences of relying too heavily on deep type inference in React and Typescript?

In the process of migrating my React + Javascript project to Typescript, I am faced with preserving a nice unidirectional flow in my existing code. The current flow is structured as follows: 1. Component: FoobarListComponent -> useQueryFetchFoobars() 2 ...

Creating Dynamic HTML/DOM in Angular 14: A Guide for Adding New Items to a List

I am currently iterating through a list of items and displaying them within a div element. These items are rendered when the page initially loads. <button (click)="addCut()" mat-raised-button color="primary">Add New Cut</button ...

Do you have any suggestions for optimizing an Angular 15 reactive form that gets filled with data from an API?

Creating an Angular 15 Reactive Form with FormGroup As I delve into the documentation to construct a form with 4 inputs that are populated with data retrieved via GET requests and then updated upon submission through PUT requests, I find that it is functi ...

Angular2: Filtering an array based on the presence of items in another array

Looking to selectively filter out entries from an object array based on certain id values within another array. I've experimented with different methods but haven't found a solution that works yet. List of id´s: list = [1,3] Array to be filte ...

Ways to implement the flow of change occurrences in the mat-select component

Seeking assistance with utilizing the optionSelectionChanges observable property within Angular Material's mat-select component. This property provides a combined stream of all child options' change events. I'm looking to retrieve the previ ...

What is the syntax for declaring a boolean or object type?

Is it possible to create a variable in TypeScript that can hold either true/false or an object of booleans? I'm still learning TS and would like some input on this syntax. variableA: { a: boolean, b: boolean } | boolean I found a workaround for now, ...