Angular 8 ngFor's keyvalue pipe and ngModels. Having issues binding values

KeyValuePipe in a nutshell:

Transforms Object or Map into an array of key value pairs.

The keyvalue pipe creates a new array from a given object, and as so, binding to it will not affect the original object.

As for your issue, instead of using the (change) event listener you can just bind ngModel to your original object, and point to it directly:

<div *ngFor="let prop of myObject | keyvalue">
      <input [(ngModel)]="myObject[prop.key]">
</div>

Hope this helps!


You can define the changeKey function like the following code.

In Component

changeKey(prevKey, newKey) {
  const value = this.obj[prevKey];
  delete this.obj[prevKey];
  this.obj[newKey] = value;
}

In HTML

<input (change)="changeKey(pref.key, $event.target.value)" [ngModel]="pref.key"><br />

I created a working example on stackblitz.

Tags:

Angular