无法将数组与 angular 中的 ngModel 绑定,因为索引是只读的

Cannot bind an array with ngModel in angular because the index is read-only

<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中不需要使用索引。如我所见,您只需使用 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>