1

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

<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

1 Answer 1

0

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.