Error encountered during Angular production build: Attempting to assign value to a reference or variable not possible

Encountering issues building the production version of my Angular app.

The IDE console only displays this message:

ERROR in Cannot assign to a reference or variable!

To successfully build, I need to include these options:

--aot=false --buildOptimizer=false 

However, even with these options, the app fails after deployment with this error message in the browser console:

ERROR TypeError: Cannot read property 'init' of undefined

This issue can be resolved by adding another option:

--optimization=false 

When attempting to build using:

npm run ng build -- --prod

A log file provides some information:

0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Backend\\nodejs\\node.exe', ...

Despite updating everything, the problem persists. The output of ng version is as follows:

Angular CLI: 8.3.4
Node: 10.15.3
OS: win32 x64
Angular: 8.2.6
...

Having examined the source code available at the link provided, I am seeking guidance on how to identify and resolve this error.


Similar query posted on ru.stackoverflow:


SOLVED:

The root cause of the error has been identified (credit to SO user ): an attempt was made to alter the value of a variable defined within a template using a custom directive.

The lack of clear error messaging complicated troubleshooting, necessitating debugging via the compiler. For more details, refer to this discussion (in Russian):

UPDATE:

Issues and PRs have been submitted to the Angular repository for resolution:

  1. No detailed error messages: issue, PR
  2. Assignment of values to template variables causing prod build failure: issue, PR

Answer โ„–1

Dealing with exceptions from the AST parser can often be a frustrating experience. These exceptions tend to lack any useful information, providing only a generic error message:

ERROR in Cannot assign to a reference or variable!

Isn't that just lovely?

Take for instance the linker (ViewBuilder) which simply points out where it struggles to build template expressions.

Turning to Google may seem like a viable option. However, you'll likely end up being directed back to checking the usage of the ngModel directive in your template.


The alternative approach involves delving into the compiler itself and debugging the issue directly. Angular utilizes

node_modules/@angular/compiler/bundles/compiler.umd.js
during compilation.

If we open this file and search for the text

Cannot assign to a reference or variable!
, we will come across the _AstToIrVisitor class and the visitPropertyWrite method containing the following line of code:

// Otherwise it's an error.
throw new Error('Cannot assign to a reference or variable!');

An exception is thrown without shedding much light on the problem ๐Ÿคจ

To better understand the situation, we can insert a console.log(ast) before the exception, where ast represents the parameter of the visitPropertyWrite function. This would log an instance of the PropertyWrite class to the console:

PropertyWrite {
  span: ParseSpan { start: 0, end: 73 },
  receiver: ImplicitReceiver { span: ParseSpan { start: 0, end: 0 } },
  name: 'translation',
  value: MethodCall {
    span: ParseSpan { start: 14, end: 73 },
    receiver: ImplicitReceiver { span: [ParseSpan] },
    name: 'getTranslationForLanguageFromArticle',
    args: [ [PropertyRead], [PropertyRead] ]
  }
}

This process leads us to examine the connection between the translation property and the

getTranslationForLanguageFromArticle
method call. By analyzing your example from Bitbucket, I uncovered the usage of "getTranslationForLanguageFromArticle" within the feed.component.html:

(change)="translation = getTranslationForLanguageFromArticle($event.value, article)"

The parser struggles because translation isn't a class property but rather a local variable accessed implicitly within the *ngVar directive.

A possible solution could involve creating a method like changeTranslation within the component and manipulating the

article.translations[indexOfCorrectArticleTranslation(article)]
there.

At least now you have a clearer direction to follow :)

Answer โ„–2

In my experience, I encountered an error when I inadvertently named a template-control the same as a binding property in my class. Here is an example of what caused the issue:

<input type="password" class="form-control" name="passwordConfirmation" #passwordConfirmation="ngModel" [(ngModel)]="passwordConfirmation"/>

In this case, "passwordConfirmation" serves as both the name of the control in the template and the name of the property/variable in the component class. This confusion led the compiler to attempt to bind to the template variable instead of the class property.

Answer โ„–3

It seems that one of the variable names is causing an issue, making it difficult to pinpoint the exact problem without thorough debugging. I recommend checking all instances of ngIf, ngModel, ngFor, etc. in your project as you may be inadvertently using the same variable name multiple times.

Answer โ„–4

I encountered a situation where [(ngValue)] was utilized instead of using [ngValue]

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

Unlocking the union of elements within a diverse array of objects

I have an array of fields that contain various types of input to be displayed on the user interface. const fields = [ { id: 'textInput_1', fieldType: 'text', }, { id: 'selectInput_1', fieldType: 'sel ...

Ways to verify that the Google Analytics code is functioning properly within an Angular 2 application

I'm just getting started with Google Analytics and I'm attempting to integrate it into my Angular 2 project. Here's how I've set it up: app.component.ts import { Component } from '@angular/core'; import {Router, NavigationEn ...

Having difficulty deploying the ASP.Net application in Visual Studio

While attempting to publish my app from Visual Studio, I encountered the following error: The command "node node_modules/webpack/bin/webpack.js --env.prod" exited with code 1. First Azure app C:...\firstazureapp C:...firstazureapp\firstaz ...

Establish a connection with MongoDB and make changes to the data

I am facing an issue while trying to update values stored in MongoDB. I thought of using mongoose to view and edit the data, but it seems like I'm encountering an error along the way. Has anyone successfully implemented this kind of task before? impo ...

What is npm's approach to managing circular dependencies?

Is npm equipped to handle circular/cyclic dependencies within a package? If so, how does it manage this issue? I've searched online but haven't found much information on this topic. There are two potential problems that come to mind: Circular ...

Having trouble triggering an alert() after a successful post to the database

As I delve into the realm of backend development, I find myself facing what seems like a simple puzzle that I just can't solve. My goal is to create a basic CRUD app to enhance my skills, so I decided to build a blog platform that could eventually be ...

What could be causing the rejection of my front-end request to the back-end service?

I am currently managing an Angular application running on port 8001 of an IIS server. This application needs to interact with two back-end .NET APIs, one on port 89 and the other on port 83, both located on the same server. There are two types of users ac ...

What is the correct way to refer to "this" within an Angular2 component template?

I'm working with an Angular2 component that looks like this: class A { filter(..) } Within the template for A, I have <.. list | pipe:filter ..> The issue arises when I call filter inside of the pipe - I don't have access to "this" w ...

Tips for customizing the CSS of a child component that has been imported from a different module in Angular 2

I have been using agm-snazzy-window from amg-snazzy-window There is a mention that I can modify the css class, but when I try to do so, it doesn't seem to work. Here is an example: map-component.html <agm-snazzy-info-window [closeWhenOthersOp ...

Numeric String Expected Error Encountered in NestJS DTO Validation

While working on my NestJS application, I encountered a validation error when making a request to the http://localhost:3000/users/authstatus endpoint. The error message displayed was: { "message": "Validation failed (numeric string is ex ...

Changing the default headless browser to chrome in Cypress: A step-by-step guide

Currently I am utilizing the Cypress framework with TypeScript for my testing. When I execute the command "npx cypress run," all of my tests are running in headless mode using Electron as the default browser. However, I am interested in running them in C ...

Issue with NgRx store: Incorrect parameter types being passed in reducer function

My goal is to implement a basic reducer, but I encountered an issue after updating app.module.ts with code I borrowed from [coursetro.com][1]. The error I received was perplexing. The error message stated that the function I attempted to pass as paramete ...

Steps for transferring .pem files to Typescript outDir

I am currently working on a NodeJS project using Typescript, and I have encountered an issue with referencing .pem files to initiate an https server. The problem arises when my code is compiled, as the .pem files are not present in the output directory. ...

Command line functionality to eliminate comments in HTML minifier

I am interested in utilizing html-minifier to compress my html documents. After executing the command npm install -g html-minifier, I have successfully installed it. However, the command sudo html-minifier rb.html --removeComments did not eliminate comme ...

Design your own Angular 2 Directive for effortless element dragging!

My goal is to develop a custom directive in Angular 2 that enables the user to drag an HTML Element based on its x position. I have drafted some pseudo code to demonstrate what I think might work, however, my experience with directives is limited and I ...

Having trouble with npm installing bower?

Attempting to set up bower with npm. Following the steps and executed the command: npm install -g bower Changed the loglevel to "info" for better visibility. The process progresses until: npm info build \\bedcoll.local\san\Home&bso ...

Fresh Gatsby version 5.2 Setup Triggering `NPM WARN` Alerts for `react-server-dom-webpack``

Following a fresh installation of Gatsby 5.2 through the Gatsby CLI, I'm seeking assistance in deciphering my terminal output which is flooded with NPM WARN flags. I have three inquiries; What is triggering these errors? Why are these errors occurri ...

Is there a way to fetch a particular object from Firebase database based on its value using AngularFire2?

Here is the database I am working with: firebase database I am trying to retrieve a dish that has its 'featured' attribute set to true (dish.feature = true). Is it possible to do this directly from the database, or do I have to retrieve all di ...

To prevent callback hell in Angular 2 when making multiple HTTP requests

Back in my Angular 1 days, I used to nest HTTP calls and react to their results like this: this.$qSessionPromise .then(() => { return this.Init(); }) .then(() => { return this.Services.GetData1("id1"); }) .then((data: model.DataType1) => ...

Is it possible to execute multiple scripts simultaneously when webpack watch is triggered?

My Current Development Setup Currently, I have set up an npm script that resembles the following: "dev":"yarn install && concurrently -k \"npm run webpack\" \"cd dist/ && node App.js\" \"npm run test\" \ ...