简体   繁体   中英

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

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM