angular - 无法将数组与 ngModel 以角度方式绑定,因为索引是只读的
问题描述
<div *ngFor="let x of options; let i = index;trackBy:trackByIdx">
<mat-form-field class="full-width" appearance="fill">
<mat-label>Option</mat-label>
<input type="input" [(ngModel)]="options[i]" matInput>
</mat-form-field>
</div>
出于某种奇怪的原因,我在尝试编辑测验表单时从模板中收到错误消息。我收到 ERROR TypeError: 0 is read-only from [(ngModel)]="options[i]",这意味着错误来自模板。
@Input() title: string;
@Input() options: string[];
@Output() titleEmitter: EventEmitter<string> = new EventEmitter<string>();
@Output() optionsEmitter: EventEmitter<string[]> = new EventEmitter<string[]>();
onAddOptions() {
if (this.options && this.options.length < 11) {
this.optionsEmitter.emit([...this.options, '']);
}
}
emitOptions(index: number) {
this.optionsEmitter.emit([...this.options.slice(0, index), this.options[index], ...((this.options[index+1]) ? this.options.slice(index + 1) : [])])
}
我不确定其余代码是否会按预期工作,因为错误是从模板中抛出的,但我希望了解它为什么会抛出错误。索引是只读的吗?它似乎来自索引,因为当我尝试编辑第二个选项时,我也得到 ERROR TypeError: 1 is read-only 。
解决方案
不需要在ngModel中使用 index 。正如我所看到的,您只需使用 for 循环将输入与值绑定即可。
您可以将您的 html 代码替换为以下行代码。这将消除你的错误,你可以实现你想要的。
<div *ngFor="let x of options; let i = index;trackBy:trackByIdx">
<mat-form-field class="full-width" appearance="fill">
<mat-label>Option</mat-label>
<input type="input" [(ngModel)]="x" matInput>
</mat-form-field>
</div>
推荐阅读
- excel - VBA 搜索功能仅在从另一个工作表触发时才有效
- cmake - 基于生成器的 cpack 条件行为
- visual-studio - VS2019:找不到类型或命名空间名称
- docker - 通过 docker compose 部署时 GitLab CI 管道失败
- xslt - XPath 如何优化“先前”轴的性能?
- php - 文件权限被拒绝(Laravel、Windows Server 2016、IIS10)
- sharepoint - 过滤文档“组(y)上的最大(x)”
- google-apps-script - 谷歌表中的 onedit 脚本仅适用于一个功能
- c++ - 这真的能确保一个数字在 1-9 之间吗?
- r - 在 R 中查找数据框范围的重叠