英文:
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
<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"
英文:
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
得分: 0
以下是翻译好的部分:
这可能不适用于最新版本。 您需要理解模板变量。 Angular-understanding template variables
将代码更改如下:
<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>
在.ts文件中,编写更新函数如下:
updateElement(value: string, index: number) {
this.list[index] = value;
}
英文:
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;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论