I was following an example from angular.io website of creating a form in angular with an input but I am stuck at an error:
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 only change I made was renaming the "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>
What's wrong in the above code?
Your problem is here:
[(ngModel)]="username" name="name"
#username="ngModel">
When you do this, you're creating a variable username
for your template, that refers to the NgModel
instance. So, when you bind ngModel
to username
the compiler thinks you're binding to the reference, not to your component's username
property, because template variables hide component properties with the same name. Change the name of the reference to usernameModel
or something like that (and remember to change it wherever you're using it, too, as in the div
that shows errors) and it should work fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With