Home > other >  Why is assigning a template variable to ngModel in Angular not working?
Why is assigning a template variable to ngModel in Angular not working?

Time:12-16

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

<div >                
    <input  type="text" [(ngModel)]="siteUrl" 
      #siteUrl="ngModel" name="siteUrl" required>

    <div *ngIf="siteUrl.invalid && (siteUrl.dirty || siteUrl.touched)">
       <div *ngIf="siteUrl.errors['required']" >
          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.

CodePudding user response:

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 >                
  <input  type="text" [(ngModel)]="siteUrl" 
    #siteUrlField="ngModel" name="siteUrl" required>

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

Here's a working stackblitz example.

  • Related