0

I have the following segment of code in a format that is quite common in Angular:

<div class="col col-xs-12 col-sm-6">                
    <input class="form-control" type="text" [(ngModel)]="siteUrl" 
      #siteUrl="ngModel" name="siteUrl" required>

    <div *ngIf="siteUrl.invalid && (siteUrl.dirty || siteUrl.touched)">
       <div *ngIf="siteUrl.errors['required']" class="red">
          siteUrl is required
       </div>
    </div>
 </div>

During transpile I get the following error:

An unhandled exception occurred: Cannot assign value "$event" to template variable "siteUrl". Template variables are read-only.

I am using Angular 13 and copied this segment of code directly from another working Angular 13 application.

koque
  • 1,830
  • 5
  • 28
  • 49

1 Answers1

1

Because your template variable name is colliding with the property you're binding ngModel to. Change your template variable name to a unique name so ngModel isn't trying to assign to it:

<div class="col col-xs-12 col-sm-6">                
  <input class="form-control" type="text" [(ngModel)]="siteUrl" 
    #siteUrlField="ngModel" name="siteUrl" required>

  <div *ngIf="siteUrlField.invalid && (siteUrlField.dirty || siteUrlField.touched)">
      <div *ngIf="siteUrlField.errors['required']" class="red">
        siteUrl is required
      </div>
  </div>
</div>

Here's a working stackblitz example.

Dean
  • 2,084
  • 17
  • 23
  • No dice, Dean. I tested your suggestion, that is not the problem. I have applied that usage in many applications, first time it is erroring out. – koque Dec 15 '22 at 20:50
  • @koque here's a [StackBlitz where I pasted in your example](https://stackblitz.com/edit/angular-ivy-bfsdpt?file=src%2Fapp%2Fapp.component.ts,src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.module.ts). It doesn't work. [Here's one where I pasted in my updated example](https://stackblitz.com/edit/angular-ivy-cdydr1?file=src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.component.ts). It works fine. – Dean Dec 15 '22 at 21:15
  • 1
    My bad, Dean, I made an error in testing your proposed solution. Surprisingly, it works perfectly. I have used my solution in hundreds of codes and it worked until now. Thanks for your help. – koque Dec 15 '22 at 21:31
  • @koque I'm not sure which version they started throwing errors but [check this link for more details](https://stackoverflow.com/questions/60128458/strange-problem-migrating-angular-8-app-to-9). – Dean Dec 15 '22 at 22:11