首页 > 解决方案 > 无法将数组与 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 。

标签: angularangular-ngmodel

解决方案


不需要在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>

推荐阅读