Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ERROR: Cannot assign value "$event" to template variable "element". Template variables are read only

Can someone please help me what is wrong with this code?

 <div *ngFor="let element of list; let index=index">
    <mat-form-field>
      <input matInput type="string" [(ngModel)]="element" name="element" #field="ngModel">
    </mat-form-field>
</div>

I am getting an error
ERROR: Cannot assign the value "$event" to template variable "element". Template variables are read only

I tried below solution

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<div *ngFor="let element of list; let index=index">
  <mat-form-field>
    <input matInput type="string" [(ngModel)]="list[index]" name="element" #field="ngModel">
  </mat-form-field>
</div>

This solution works but when I try to edit the input field it takes only one character at a time, for every character I need to click inside the input box and then type

>Solution :

This may not work with the latest version. You need to understand template variables. Angular-understanding template variables

Change the code like below

<div *ngFor="let element of list; let index=index">
<mat-form-field>
  <input matInput type="string" [ngModel]="element" (change)="updateElement($event.target.value,index)" name="element" #field="ngModel">
</mat-form-field>
</div>

In .ts file, write update function as

updateElement(value:string,index:number) {
  this.list[index] = value;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading