An error occurred: Assignment to a reference or variable is not allowed! This error was triggered by the visitPropertyWrite function in the _AstToIrVisitor

I encountered an issue while attempting to implement a form in Angular based on a tutorial from the angular.io website. The error message I received is as follows:

compiler.js:26390 Uncaught Error: Cannot assign to a reference or variable! at _AstToIrVisitor.visitPropertyWrite (webpack-internal:///./node_modules/@angular/compiler/esm5/compiler.js:26611:23) at PropertyWrite.visit (webpack-internal:///./node_modules/@angular/compiler/esm5/compiler.js:4900:24) at convertActionBinding (webpack-internal:///./node_modules/@angular/compiler/esm5/compiler.js:26035:45) at eval (webpack-internal:///./node_modules/@angular/compiler/esm5/compiler.js:28635:22) at Array.forEach () at ViewBuilder._createElementHandleEventFn (webpack-internal:///./node_modules/@angular/compiler/esm5/compiler.js:28631:18) at nodes.(anonymous function) (webpack-internal:///./node_modules/@angular/compiler/esm5/compiler.js:28050:27) at eval (webpack-internal:///./node_modules/@angular/compiler/esm5/compiler.js:28576:22) at Array.map () at ViewBuilder._createNodeExpressions (webpack-internal:///./node_modules/@angular/compiler/esm5/compiler.js:28575:56)

The modification I made was changing the attribute "name" to "username".

dashboard.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {

  username: string;
  submitted = false;

  constructor() { 
  }

  ngOnInit() {
  }

  onSubmit() { this.submitted = true; }

}

dashboard.component.html

<div class="row justify-content-md-center">
    <div class="col col-lg-12">
      <form (ngSubmit)="onSubmit()" #usernameForm="ngForm" >
        <div class="form-group">
          <label for="username">Name</label>                    

          <input type="text" class="form-control" id="name"
          required
          [(ngModel)]="username" name="name"
          #username="ngModel">

          <div [hidden]="username.valid || username.pristine"
              class="alert alert-danger">
            Name is required
          </div>
        </div>
        <button type="submit" class="btn btn-success">Submit</button>
      </form>
    </div>
</div>

Can you identify the issue in the provided code snippet?

Answer №1

Identifying the root of your issue:

[(ngModel)]="username" name="name"
      #username="ngModel">

The problem arises from defining a variable username within your template that points to the NgModel instance. Consequently, when you associate ngModel with username, the compiler interprets it as referencing the variable, not your component's username property, since template variables can overshadow component properties of the same name. To resolve this, adjust the name of the reference to something like usernameModel (and remember to make this change consistently throughout your code, including the div displaying errors), and the issue should be resolved.

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

What is causing the duplication of leaves when using this DFS implementation?

I created an algorithm to compare if two trees have the same leaves. https://i.sstatic.net/lpO2C.png Both trees display matching leaf numbers in the exact order, resulting in a true outcome. Below is the code that I formulated: function leafSimilar(root ...

Develop a wrapper for a function with multiple variations in TypeScript

Encountering an issue with the code below while attempting to create a proxy for a function with multiple overloads: // The target function function original (a: number): boolean; function original (a: string): boolean; function original (a: boolean): bool ...

Tips for effectively managing asynchronous tasks

I keep getting different numbers every time my code runs. Can you tell me if I'm doing this the right way? Here's the code: export class GetPlanetsService { url='https://swapi.co/api/planets/?page='; planets:Planet[]=[]; headers: ...

Determining the best application of guards vs middlewares in NestJs

In my pursuit to develop a NestJs application, I aim to implement a middleware that validates the token in the request object and an authentication guard that verifies the user within the token payload. Separating these components allows for a more organi ...

Monitoring Object Changes in Angular 4

ETA: I am aware of different methods for monitoring my form for alterations. However, that is not the focus of my inquiry. As indicated by the title, my question pertains to observing changes within an object. The application displayed below is solely for ...

Incorrect Node.js version identified

I have been facing a challenge trying to integrate my projects developed with Spring and Angular using Maven. The issue arises with the Node.js version: [ERROR] Node.js version v8.11.3 detected. [ERROR] The Angular CLI requires a minimum Node.js version of ...

Include an additional query parameter called login_hint in microsoft-adal-angular6 directly from an Angular component

Utilizing the provided package https://www.npmjs.com/package/microsoft-adal-angular6 for logging into azure AD has been successful. In the app module, I have configured the extraQueryParamter as shown below: MsAdalAngular6Module.forRoot({` tenant: " ...

Using Typescript: accessing all properties from a specified type while excluding one

Currently working in React, I am interested in extending my type from another, with the exception of some props. This is how I want to approach it : import React from 'react'; import { withTheme } from 'styled-components'; import SvgBa ...

Exploring the Flow of Angular 5 HttpInterceptor

Implementing HttpInterceptor in one of my Angular applications to display a spinner for every request has been successful. However, I have encountered an issue with displaying an Error modal using a notificationService that utilizes SweetAlert. The code sn ...

Unable to retrieve data header in the Angular 10 build version

I have a code snippet for an HTTP request: return this.http.post<any>(this.path.userRoot + '/logIn/random', body, { withCredentials: true, responseType: "json", observe: 'respon ...

Executing several asynchronous functions in Angular 2

I am currently developing a mobile app and focusing on authentication. In order to display data to the user on my home page, I need to connect to various endpoints on an API that I have created. Although all endpoints return the correct data when tested i ...

Difficulty in styling with ag-Grid in SharePoint Framework (SPFX) combined with Angular

I'm currently delving into the world of custom SharePoint Web Parts using SharePoint Framework (SPFX) in combination with Angular Elements. One roadblock I've encountered is that when trying to implement ag-Grid, the style definitions for the gri ...

Best Practices for Implementing Redux Prop Types in Typescript React Components to Eliminate TypeScript Warnings

Suppose you have a React component: interface Chat { someId: string; } export const Chat = (props: Chat) => {} and someId is defined in your mapStateToProps: function mapStateToProps(state: State) { return { someId: state.someId || '' ...

I require clarity on this befuddling syntax that feels like descending into

I came across this example in the official documentation at https://angular.io/guide/form-validation#custom-validators return (control: AbstractControl): {[key: string]: any} => { const forbidden = nameRe.test(control.value); return forbidden ...

Typescript - Keeping a log of object keys along with their corresponding key type values

Imagine having the following scenario where you need to create an object with keys that are transformed versions of the original type's values: export type CCDTypes = { AuthorisationCaseEvent: AuthorisationCaseEvent, AuthorisationCaseField: Author ...

Issue with Socket.IO: socket.on not executed

Recently, I devised a custom asynchronous emitter for implementing a server -> client -> server method. Regrettably, the functionality is not meeting my expectations. Although it emits the event, it fails to execute the callback as intended. Upon a ...

Issue with initial navigation in MVC app causing Angular app routing to fail

Encountering a problem with navigating within an Angular app hosted on an MVC page. While most of the functionality is working smoothly, there is one scenario where the URL changes but the new page is not displayed. Let's simplify the setup (this iss ...

The meta title is not visible in the view page source, but it can be found when inspecting the webpage

Struggling to make my meta tags dynamic by integrating angular universal was quite a journey. Despite facing numerous challenges, I managed to successfully incorporate angular universal into my project. Running the project using npm run dev:ssr seemed prom ...

Angular's unconventional solution to Firebase

I've been having trouble integrating Firebase with Angular. When I encountered an error stating that firebase.initializeApp is not a function, I hit a roadblock. const firebase = require("firebase"); (Previously, it was written as: import * as fireb ...

Fetching values from JSON object using Key in Angular

Here is the code snippet for the markup and component in question: new.component.html <a routerLink="{{sub.name}}" routerLinkActive="active">{{sub.name}}</a> old.component.ts data; this.route.params.subscribe((params:any) => {console.lo ...